首页 > 解决方案 > 从二维列表中保存的三元组单词构造句子

问题描述

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

到目前为止的代码:

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)

我的二维列表:

[['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 个单词或无法选择其他三联组时结束。

有任何想法吗?

标签: pythonarrayspython-3.xlistword

解决方案


要选择随机三元组:

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]

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


推荐阅读