0

別のテキスト ファイルに含まれるリストを処理しようとしています。ファイルを読み取り、ファイルの内容を含む出力を生成することはできますが、生成された出力は入力と同じ未処理のバージョンです。作業しているモジュール内にリストが含まれている場合、この問題は発生しません。プロセスは正常に実行されます。入力ファイルを使用すると問題が発生する理由はありますか?

これは正常に実行されます (注意してください - 両方の実行で、「正しい」は同じモジュール内の関数です)。

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()

問題が何であるかについて何か考えはありますか?

4

2 に答える 2

0

ファイル形式を指定すると、先頭に手動で「words =」を追加できます。たとえば、次のようになります。

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

text.txt ではなく text.py として保存します。

その後、次のコマンドを使用して、実際のスクリプトにリストをインポートできます。

from text import words

解析は一切必要ありません

于 2012-12-03T19:02:31.370 に答える
0

1 つの違いは、2 番目の例では、ファイルlineの改行文字 ( ) が保持されることです。\n最初の例には、これらの文字がありません。

また、text.txt1行に1語でフォーマットされていると思います。

PS改行(およびその他の空白)を削除するには:

def spelltest():
    for line in infile:
        print correct(line.strip())
于 2012-12-03T15:12:51.860 に答える