3 回答

TA貢獻2003條經驗 獲得超2個贊
我假設您的問題是創建temp文件中定義的所有可能的單詞對。這稱為置換,您已經在使用該itertools.permutations函數
如果需要將輸出實際寫入文件,則代碼應為以下內容:
代碼:
import itertools
f = open("temp","r")
lines = [line.split(' ')[-1].strip() for line in f] #1
pairs = list(itertools.permutations(lines, 2)) #2
r = open('result', 'w') #3
r.write("\n".join([" ".join(p) for p in pairs])) #4
r.close() #5
該
[line.split(' ')[-1].strip() for line in f]
會讀取整個文件,并為每個readed線,它會分裂它周圍的空格字符,選擇該行的最后一個項目(負指標就像-1
在列表中向后行走),刪除任何尾隨空格(像\n
),并把所有的一個列表中的行像您已經做過的那樣生成對,但是現在它們沒有拖尾了
\n
打開
result
文件進行寫入將用空格(
" "
)分隔的對連接起來,用a將每個結果(一行)連接起來\n
,然后寫入文件關閉文件(因此刷新它)

TA貢獻1830條經驗 獲得超9個贊
import itertools
with open("temp.txt", "r") as f:
words = [item.split(' ')[-1].strip() for item in f]
pairs = list(itertools.permutations(words, 2))
print(pairs)
印刷品(pprint用于提高可讀性):
[('the', 'of'),
('the', 'to'),
('the', 'and'),
('the', 'bank'),
('of', 'the'),
('of', 'to'),
('of', 'and'),
('of', 'bank'),
('to', 'the'),
('to', 'of'),
('to', 'and'),
('to', 'bank'),
('and', 'the'),
('and', 'of'),
('and', 'to'),
('and', 'bank'),
('bank', 'the'),
('bank', 'of'),
('bank', 'to'),
('bank', 'and')]

TA貢獻1826條經驗 獲得超6個贊
一些改進的解釋
import itertools
with open('temp.txt', 'r') as fobj_in, open('out.txt', 'w') as fobj_out:
words = (item.split()[-1] for item in fobj_in if item.strip())
for pair in itertools.permutations(words, 2):
fobj_out.write('{} {}\n'.format(*pair))
解釋
with open('temp.txt', 'r') as fobj_in, open('out.txt', 'w') as fobj_out:
我們打開兩個文件,一個用于讀取,一個在的幫助下編寫with。這保證了with即使我們在該塊的某個位置出現異常,只要我們離開該塊的縮進,這兩個文件都將被關閉。
我們使用列表理解來獲取所有單詞:
words = [item.split()[-1] for item in fobj_in if item.strip()]
item.split()[-1]刪除任何空格,并為我們提供行中的最后一個條目。請注意,它也在\n每行的結尾處取下。不需要.strip()這里。item.split()通常比item.split(' ')它更好,因為它也可以在多個空間和制表符中使用。我們仍然需要確保該行不是空的if item.strip()。如果刪除所有空格后什么也沒留下,那么我們item.split()[-1]就沒有話語了,并且會給出和索引錯誤。只需轉到下一行并丟棄該行即可。
現在我們可以遍歷所有對,并將它們寫入輸出文件:
for pair in itertools.permutations(words, 2):
fobj_out.write('{} {}\n'.format(*pair))
我們要求迭代器一次給我們下一個單詞對一對,然后將此對寫入輸出文件。無需將其轉換為列表。將其中.format(*pair)的兩個元素解包pair,.format(pair[0], pair[1])對于與我們兩個元素對應的那對等價。
業績說明
第一種直覺可能是也使用生成器表達式從文件中讀取單詞:
words = (item.split()[-1] for item in fobj_in if item.strip())
但是時間測量表明,列表理解比生成器表達式要快。這是由于無論如何都要itertools.permutations(words)消耗迭代器words。首先創建一個列表,避免了再次遍歷所有元素的工作。
添加回答
舉報