【问题标题】:Structure sentences from words of triplets saved in a 2D list从二维列表中保存的三元组单词构造句子
【发布时间】:2021-01-10 19:00:04
【问题描述】:

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

到目前为止的代码:

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

有什么想法吗?

【问题讨论】:

    标签: python arrays python-3.x list word


    【解决方案1】:

    要随机选择一个三元组:

    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]
    

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

    【讨论】:

    • 嗯嗯嗯好的。在我看来,我使用的文本在根据现有单词复制新文本方面太差了。但出于测试目的,我在同一个 txt 文件中复制了“Python 是解释型”这句话,并且我收到了结果。即 (['Python', 'is', 'an']) -> ['is', 'an'] -> ['is', 'an', 'interpreted'] -> ['an', '解释']。我想我必须为我的结果使用更好的输入。至少我是对的到这一步???
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多