首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从二维表中保存的三元组单词构造句子

从二维表中保存的三元组单词构造句子
EN

Stack Overflow用户
提问于 2021-01-11 03:00:04
回答 1查看 32关注 0票数 0

我目前有一个文本,它的单词保存为二维列表中的三元组。

到目前为止的代码:

代码语言:javascript
复制
with open(r'c:\\python\4_TRIPLETS\Sample.txt', 'r') as file:
    data = file.read().replace('\n', '').split()
    lines = [data[i:i + 3] for i in range(0, len(data), 3)]
print(lines)

我的2D列表:

代码语言:javascript
复制
[['Python', 'is', 'an'], ['interpreted,', 'high-level', 'and'], ['general-purpose', 'programming', 'language.'], ["Python's", 'design', 'philosophy'], ['emphasizes', 'code', 'readability'], ['with', 'its', 'notable'], ['use', 'of', 'significant'], ['whitespace.', 'Its', 'language'], ['constructs', 'and', 'object-oriented'], ['approach', 'aim', 'to'], ['help', 'programmers', 'write'], ['clear,', 'logical', 'code'], ['for', 'small', 'and'], ['large-scale', 'projects.']]

我想创建一个Python代码,它从这些三元组中随机选取一组,然后尝试通过使用最后两个单词并选择以这两个单词开头的三元组来创建一个新的随机文本。最后,我的程序在写入200个单词时结束,或者不能选择其他三元组。

有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-11 03:24:11

要拾取随机的三元组,请执行以下操作:

代码语言:javascript
复制
import random

triplet = random.choice(lines)
last_two = triplet[1:3]

要继续挑选,请执行以下操作:

代码语言:javascript
复制
while True:
    candidates = [t for t in lines if t[0:2] == last_two]
    if not candidates:
        break

    triplet = random.choice(candidates)
    last_two = triplet[1:3]

我将把保存输出和长度停止的标准留给你。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65657288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档