我目前有一个文本,它的单词保存为二维列表中的三元组。
到目前为止的代码:
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列表:
[['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个单词时结束,或者不能选择其他三元组。
有什么想法吗?
发布于 2021-01-11 03:24:11
要拾取随机的三元组,请执行以下操作:
import random
triplet = random.choice(lines)
last_two = triplet[1:3]要继续挑选,请执行以下操作:
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]我将把保存输出和长度停止的标准留给你。
https://stackoverflow.com/questions/65657288
复制相似问题