2012-12-03 25 views
0

我試圖處理包含在單獨的文本文件中的列表。我能夠讀取文件,並生成包含文件內容的輸出,但生成的輸出是未處理的版本,與輸入相同。 當列表包含在我正在使用的模塊中時,我不會遇到此問題 - 該過程成功運行。任何想法爲什麼使用輸入文件導致問題?處理Python模塊中的列表工作,但在單獨的文件中處理相同的列表不是

這成功運行(請注意 - 兩個運行,「正確」是在同一模塊中的一個函數):

import sys 
sys.stdout = open('out.txt','w') 

def spelltest(): 
    for i in test: 
     print correct(i) 

test = ['acess','accesing','accomodation','acommodation','acomodation', 
'acount','adress','adres','addresable','aranged','arrainged', 
'arrangeing','aranging','arragment','articals', 
'annt','anut','arnt','auxillary','avaible', 
'awfall','afful','basicaly','begining', 
'benifit','benifits','beetween', 
'bicycal','bycicle','bycycle'] 

if __name__ == '__main__': 
    print spelltest() 

這不:

import sys 
sys.stdout = open(r'C:\Python26\out.txt','w') 

infile = open('C:\\Python26\\text.txt','r') 

def spelltest(): 
    for line in infile: 
     print correct(line) 

if __name__ == '__main__': 
    print spelltest() 

任何思考什麼問題可能是?

回答

0

一個區別是,在第二個示例中,line將從您的文件中保留換行符(\n)。第一個例子沒有這些字符。

此外,我假設text.txt格式化爲每行一個字。

P.S.要刪除換行符(和其他的空格):

def spelltest(): 
    for line in infile: 
     print correct(line.strip()) 
+0

是的,我應該說:

之後,你可以導入你的實際腳本列表中。 text.txt格式化爲每行一個字。我嘗試重新格式化text.txt而不使用換行符,但這導致out.txt內沒有生成輸出。關於如何解決這個問題的任何想法,如果它是關於換行符的?是否應循環列表中的項目,而不是一行一行? – user1185790

+0

@ user1185790:只需調用'strip()' - 查看更新的答案。 – NPE

+0

我試過了。它僅刪除輸出內每行之間的間距,但沒有成功「糾正」文本。 – user1185790

0

鑑於你的文件格式,你可以手動添加「字樣=」開頭,如:

words = ['acess', 'accesing', 'accomodation', 'acommodation', 'acomodation', 'acount', 'adress', 'adres', 'addresable', 'aranged', 'arrainged'] 

,然後將其保存爲文本。 py而不是text.txt。

from text import words

和任何將不需要解析