2017-10-14 15 views
0

ファイル内のすべての行を繰り返し処理してから、各行をリストに追加し、そのリストを削除します(空白と\ n ')、最後にそれらのリスト項目を1つの大きなリストに追加します。このリストには、ファイル内のすべての行のすべての文からすべての単語が含まれます。 ここにあるコードは、1つの詳細を除いて、何らかの理由で最初の行をスキップします。ファイル内の最初の行を読み取っていない

def counter(words): 
    frequency = {} 
    for word in words: 
     if word not in frequency: 
      frequency[word] = 1 
     elif word in frequency: 
      frequency[word] += 1 
    return frequency 


def main(): 
    print("This program shows the frequency of words in a file.\n" 
      "Could you please enter the file name, without extension?") 
    file_name = input('') + '.txt' 
    with open(file_name, "r") as word_file: 
     words = [] 
     for lines in word_file: 
      for line in lines: 
       line = word_file.readline() 
       temp_words = line.split() 
       print(temp_words) 
       for word in temp_words: 
        words.append(word) 
    print(counter(words)) 

これは、全体のコードですが、皆さんはyouu感謝、主な機能に焦点を当てる必要があります!

答えて

4

いくつかの冗長性があります:

for lines in word_file: # this will move the iterator one forward 
    for line in lines: # this actually iterates through the chars in the line 
    line = word_file.readline() # but this moves the iterator ahead, too 

以下は、forループを交換するために十分でしょう。

from collections import Counter 
with open(file_name, "r") as word_file: 
    c = Counter(word for line in word_file for word in line.split()) 
print(c) 
+0

感謝:

for line in word_file: words.extend(line.split()) 

はところで、あなたのコアプログラムのように書くことができます。あなた。 私はまだpythonでnoobです; p (私はできるだけ早くあなたの答えを与えるでしょう、10分以上待たなければならない) – GotYa

関連する問題