python - 从二维列表中保存的三元组单词构造句子
问题描述
我目前有一个文本,其单词保存为二维列表中的三元组。
到目前为止的代码:
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 个单词或无法选择其他三联组时结束。
有任何想法吗?
解决方案
要选择随机三元组:
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]
我将把输出的保存和长度停止标准留给你。
推荐阅读
- matplotlib - Latex \textbar 在 matplotlib 中打印为 'j'
- reactjs - 使用 Laravel 6+ 在 react-table (v7) 中使用分页进行完全受控的服务器端过滤
- python - 如何根据条件将python数组拆分为不同的数组?
- javascript - 如何检查提示中是否有数字,因为所有东西都是提示中的字符串?
- visual-studio-code - 我正在尝试对 vscode 的编辑区域进行一些有趣的更改。我想知道API是否支持以下两个功能?
- python - 为什么执行自己的 tflite 模型时 Coral USB 不运行?
- batch-file - 如何使用 shell 脚本隐藏地运行批处理文件?
- php - 出乎意料的结束。找不到错在哪里
- javascript - 我如何关注下一个元素
- c - 为什么即使我正确使用了浮点数据类型和说明符,浮点值也给了我 0 值