【发布时间】:2021-01-12 19:07:13
【问题描述】:
我目前有一个文本,其单词保存为二维列表中的三元组。
我的二维列表:
[['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 个单词或无法选择其他三元组时结束。
到目前为止的代码:
import random
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)]
random.shuffle([random.shuffle(i) for i in lines])
first_triplet = random.choice(lines)
last_two = first_triplet[1:3]
output_text=[]
while True:
candidates = [t for t in lines if t[0:2] == last_two]
if not candidates:
break
next_triplet = random.choice(candidates)
last_two = next_triplet[1:3]
output_text.append(next_triplet)
我无法自动执行搜索匹配项并将它们存储在新列表中的重复过程。
有什么想法吗?
【问题讨论】:
标签: python arrays python-3.x list 2d