如何生成文本文件中所有可能的单词

rbu*_*rnz 1 python text dictionary python-3.x

我想从文本文件生成所有可能的单词,但我的代码不正确。

我现有的代码:

file = open('../data.txt')
for line in file.readlines():
    line = line.strip()

    for line1 in file.readlines():
        line1 = line1.strip()      
        print ("{} {}".format(line, line1))
Run Code Online (Sandbox Code Playgroud)

data.txt #-- 我的文本格式的数据文件

hero
muffin
ego
abundant
reply
forward
furnish
Run Code Online (Sandbox Code Playgroud)

需要的输出:#--生成的结果

hero muffin
hero ego
hero abundant
hero reply
hero forward
hero furnish

muffin hero
muffin ego
muffin abundant
muffin reply
muffin forward
muffine furnish

ego hero
ego muffin
so on...
Run Code Online (Sandbox Code Playgroud)

Sam*_*ord 5

尝试在嵌套循环中多次读取同一文件句柄是行不通的,因为您将在第一次通过内部循环时到达文件末尾,尽管您可以通过关闭并重新打开文件位于外循环内,没有理由这样做(它既过于复杂又不必要地慢)。

相反,只需将所有单词读入列表(一次,这样您就不会浪费时间一遍又一遍地从磁盘中重新读取相同的信息)并用于itertools.permutations生成该列表的所有 2 个单词的排列。

import itertools

with open("data.txt") as f:
    words = [word.strip() for word in f]

for p in itertools.permutations(words, 2):
    print(*p)
Run Code Online (Sandbox Code Playgroud)

印刷:

hero muffin
hero ego
hero abundant
hero reply
hero forward
hero furnish
muffin hero
muffin ego
muffin abundant
...
Run Code Online (Sandbox Code Playgroud)