亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從列表中創建單詞對列表

如何從列表中創建單詞對列表

慕容708150 2021-03-21 17:15:53
我在文件“ temp”中有一個單詞列表: 1. the  2. of 3. to 4. and 5. bank等等我如何提高其可讀性?import itertoolsf = open("temp.txt","r")lines = f.readlines()pairs = list(itertools.permutations(lines, 2))print(pairs)我迷路了,請幫忙。
查看完整描述

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

  1. [line.split(' ')[-1].strip() for line in f]會讀取整個文件,并為每個readed線,它會分裂它周圍的空格字符,選擇該行的最后一個項目(負指標就像-1在列表中向后行走),刪除任何尾隨空格(像\n),并把所有的一個列表中的行

  2. 像您已經做過的那樣生成對,但是現在它們沒有拖尾了 \n

  3. 打開result文件進行寫入

  4. 將用空格(" ")分隔的對連接起來,用a將每個結果(一行)連接起來\n,然后寫入文件

  5. 關閉文件(因此刷新它)


查看完整回答
反對 回復 2021-03-31
?
慕標琳琳

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')]


查看完整回答
反對 回復 2021-03-31
?
躍然一笑

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。首先創建一個列表,避免了再次遍歷所有元素的工作。


查看完整回答
反對 回復 2021-03-31
  • 3 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號