我目前有一个文本,其单词另存为2D列表中的三胞胎。
我的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个单词或无法选择其他三元组时,程序结束。
到目前为止的代码:
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)
我无法自动执行重复的搜索匹配并将它们存储在新列表中的过程。
有任何想法吗?
您可以使用递归函数(更改了代码的某些部分,请检查注释):
import random
#adding ["is", "an", "experiment"] to check if it works (no other triplet were present that satisfy the condition)
lines = [['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.'], ["is", "an", "experiment"]]
first_triplet = ['Python', 'is', 'an'] # random.choice(lines)
def appendNextTriplet(output_text, lines):
if len(output_text) >= 200:
return output_text
candidates = [t for t in lines if t[:2] == output_text[-2:]]
if not candidates:
return output_text
next_triplet = random.choice(candidates)
output_text += next_triplet # changed from append to concatenation, it was not correct
return appendNextTriplet(output_text, lines)
print(appendNextTriplet(first_triplet, lines)) # ['Python', 'is', 'an', 'is', 'an', 'experiment']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句