2017-02-15 97 views
-3

我讀了一個文本文件。內容,我刪除標點符號,全部改爲小寫,最後,我在一個新行上打印每個單詞。但我現在遇到的問題是按字母順序排序這些內容,之後我將保存在一個新的文本文件中。現在,我無法使用(排序方法),每次輸入.method-accessifier時,排序方法都不怎麼樣。所以我的問題是,在我之前所做的早期文本操作之後,我如何按字母順序對它們進行排序?用python對文本文件中的內容進行排序

punctuations = '''!()-[]{};:'"\,<>./[email protected]#$%^&*_~''' 
no_punct = "" 

#Open file 
file = "research.txt" 
f = open(file , 'r+') 

#read file 
contentOfFile = f.read() 


#Remove punctuations from file content 
for char in contentOfFile: 
    if char not in punctuations: 
     no_punct = (no_punct + char) 


#print "Output of formatted document is" 
for word in no_punct.lower().split(): 
    print word 

隨着上述和後續的幫助,我終於能夠實現里程碑。但是我注意到,如果我在控制檯上打印,它會打印出來,但是當我嘗試創建新文件並將文字保存爲顯示在控制檯上時,這些文字在保存到新文件時沒有格式化。但是,所有的單詞都保存在一條長長的直線上。在創建名爲「newFile.txt」的新文本文件後,我添加了nf.write(word)。我認爲這會自動將每個單詞添加到textFile格式和每個新行。這是錯的嗎?謝謝。

punctuations = '''!()-[]{};:'"\,<>./[email protected]#$%^&*_~''' 
no_punct = "" 

#Open file 
file = "research.txt" 
f = open(file , 'r+') 


#read file 
contentOfFile = f.read() 


#Remove punctuations from file content 
for char in contentOfFile: 
    if char not in punctuations: 
     no_punct = (no_punct + char) 


#create new file to save formatted words to 
newFile = "newFile.txt" 
nf = open(newFile , 'w+') 


#write words to the new textFile 
for word in sorted(no_punct.lower().split()): 
    nf.write(word) 


    #print word 
+0

@ZdaR,你是什麼意思的排序(列表)?沒有'排序'內置功能。 –

+0

是否要按字母順序對每個單詞或每行進行排序? –

+0

感謝您的回覆。對不起,我的解釋不是很清楚。雖然,我的問題得到了答案@pschill – user3761841

回答

0

你可以使用sorted

for word in sorted(no_punct.lower().split()): 
    print word 

如果你想要的結果寫入由線文件中的行,你可以試試這個:

with open("newFile.txt", "w") as f: 
    for word in sorted(no_punct.lower().split()): 
     f.write(word + os.linesep) 

當然,你需要添加import os在您的文件的開頭,以便找到換行符os.linesep

+0

非常感謝。這對我來說工作得很好。 – user3761841

+0

非常感謝.... – user3761841

+0

並將這個新的排序文字保存到文本文件?我該如何解決它?我剛剛使用這種格式'f = open(「newText.txt」,「w」)' – user3761841

-1
word_in_file = no_punct.lower().split() 
word_in_file.sort() 

這是否對你的工作?

+0

看着我的分數,我認爲答案是否定的:p什麼不行? – rmeertens

+0

其實它確實。我使用了上面用戶的答案。你的確按字母順序打印出來,但要求每個單詞都必須打印在新的一行上。但是那說,你的工作很好。謝謝... – user3761841

相關問題