2016-03-29 87 views
-2

以下代碼列出了文本文件中每個單詞的出現情況。現在我想打開一個類似的輸出文件,但按照字母順序在一個單獨的輸出文件中。我的第一步是什麼?Python:你如何打開一個單獨的輸出文件?

print("What's the name of the file?") 
    file_name = input() 
    file = open(file_name, 'r') 
    wordcount={} 
    for word in file.read().split(): 
     if word not in wordcount: 
      wordcount[word] = 1 
     else: 
      wordcount[word] += 1 
    for a,b in wordcount.items(): 
     print(a, b) 
+0

使用的語言?? –

+0

@MM我的道歉,Python是語言。 – rez

+0

你能否讓問題更清楚一點?你有什麼特別的想法,以字母順序 – Natecat

回答

1

您的第一步將顯然按字母順序排列單詞。爲了做到這一點,你可以利用排序方法中建立的pythons。首先,使用words=wordcount.keys()獲取字典中的密鑰列表(使用words=wordcount.keys()),然後您可以按照字母順序使用​​之類的字詞對該字詞列表進行排序。

1
txt='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' 
wordcount={} 
for word in txt.split(): 
    if word not in wordcount: 
     wordcount[word] = 1 
    else: 
     wordcount[word] += 1 

list1=[]   
for a,b in wordcount.items(): 
    # print(a, b) 
    list1.append([ a.lower(),b]) 

print sorted(list1, key=lambda x: x[0])  

輸出:

[['ad', 1], ['adipiscing', 1], ['aliqua.', 1], ['aliquip', 1], ['amet,', 1], ['anim', 1], ['aute', 1], ['cillum', 1], ['commodo', 1], ['consectetur', 1], ['consequat.', 1], ['culpa', 1], ['cupidatat', 1], ['deserunt', 1], ['do', 1], ['dolor', 2], ['dolore', 2], ['duis', 1], ['ea', 1], ['eiusmod', 1], ['elit,', 1], ['enim', 1], ['esse', 1], ['est', 1], ['et', 1], ['eu', 1], ['ex', 1], ['excepteur', 1], ['exercitation', 1], ['fugiat', 1], ['id', 1], ['in', 3], ['incididunt', 1], ['ipsum', 1], ['irure', 1], ['labore', 1], ['laboris', 1], ['laborum.', 1], ['lorem', 1], ['magna', 1], ['minim', 1], ['mollit', 1], ['nisi', 1], ['non', 1], ['nostrud', 1], ['nulla', 1], ['occaecat', 1], ['officia', 1], ['pariatur.', 1], ['proident,', 1], ['qui', 1], ['quis', 1], ['reprehenderit', 1], ['sed', 1], ['sint', 1], ['sit', 1], ['sunt', 1], ['tempor', 1], ['ullamco', 1], ['ut', 1], ['ut', 2], ['velit', 1], ['veniam,', 1], ['voluptate', 1]] 
0

如何試圖用collections,做這樣的事情進行排序基於密鑰的字典。

import collections 
wordcount = collections.OrderedDict(sorted(wordcount.items())) 

然後你可以循環遍歷每一個寫它的文件。

outPath = "PathToOutFile" 

outFile = open(outPath,"w"); 
for a,b in wordcount.items(): 
    outFile.write("{:s} {:d}\n".format(a,b)) 
相關問題