我想從文本檔案中生成所有可能的單詞,但我的代碼不正確。
我現有的代碼:
file = open('../data.txt')
for line in file.readlines():
line = line.strip()
for line1 in file.readlines():
line1 = line1.strip()
print ("{} {}".format(line, line1))
data.txt #--我的文本格式的資料檔案
hero
muffin
ego
abundant
reply
forward
furnish
需要的輸出:#-- 生成的結果
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...
uj5u.com熱心網友回復:
嘗試在嵌套回圈中多次從同一個檔案句柄中讀取是行不通的,因為您將在第一次通過內部回圈時到達檔案末尾,盡管您可以通過關閉并重新打開來使其作業檔案在外回圈中,沒有理由這樣做(它既過于復雜又不必要地慢)。
相反,只需將所有單詞讀入一個串列(一次,這樣您就不會浪費時間一遍又一遍地從磁盤重新讀取相同的資訊)并用于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)
印刷:
hero muffin
hero ego
hero abundant
hero reply
hero forward
hero furnish
muffin hero
muffin ego
muffin abundant
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/488126.html
標籤:Python python-3.x 字典 文本
下一篇:從字典中列印鍵值對
