2017-03-26 15 views
0

問題が発生しています。 (今後の試験のレビューをしています)。最初の質問は、各行のテキストの単語の量を出力ファイルに出力するように求めました。これは簡単な作業でした。 (私が使用したコードを提供していません)。別の同様の質問は、テキストの各行にユニークな単語の数(数)を表示することでした。私が得ることができた最も遠いものは、リストに単語を追加し、リストの長さを印刷することでした...しかし、それは各繰り返しを追加することに終わります。それで7,14,21が印刷されます。 7,7,7の代わりに(ちょうどexapainを助けるための例として)私は正しく動作するようにこのコードを修正するつもりですか?私は過去30分間試しています。どんな助けもありがとう!各行の単語の数のPython入出力ファイル

コード:各行(失敗)でユニークな単語の数について

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    for line in inf: 
     wordlst = line.split() 
     count = len(wordlst) 
     outf.write(str(count)+'\n') 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 

コード:

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    unique = [] 
    for line in inf: 
     wordlst = line.split() 
     for word in wordlst: 
      if word not in unique: 
       unique.append(word) 
     outf.write(str(len(unique))) 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 
+0

forループ内で '' unique'''を定義してください。 –

答えて

2

最初の作品はsetをしようとした場合:

def uniqueWords(inFile,outFile): 
    inf = open(inFile,'r') 
    outf = open(outFile,'w') 
    for line in inf: 
     wordlst = line.split() 
     count = len(set(wordlst)) 
     outf.write(str(count)+'\n') 

    inf.close() 
    outf.close() 
uniqueWords('turn.txt','turnout.txt') 
+0

oh ...これはずっと簡単でした私がLOLをやろうとしていたものよりも。どうもありがとう! –

+0

あなたは大歓迎です:) – zipa

+0

@RoryDaultonヘッドアップありがとう。私はまだ質問を投稿していませんが、あなたのアドバイスを心に留めておきます:) – zipa

関連する問題