2017-01-10 8 views
0

テキストファイルから単語の数を数えるためのプログラムを作成する必要があります。Python - 単語の数を数えるアプリケーション

だから、私の計画:

-userは、txtファイルの名前を入力し、

それは小文字-make、変数 'テキスト' に

-searchそれをロードし-app '/' '#'や空白などのような記号のない単語だけアルファ文字列

-

- すべての単語を表示すると、1番目に使用回数が最も多く、1回以上使用する必要があります。

どのように最小長+3の単語を含むように変更するには?例:in、on、on < - list、word、appear、clearを含めるべきではありません。< - を含める必要があります。あなたは以下の3つの文字で単語を削除したい場合は

from collections import Counter 
import re 


def open_file(): 
    file_name = input("Enter a filename: ") # enter name of file which should be open 
    with open(file_name) as f: # it should exist in project folder 
     text = f.read() # load file into var text 
    f.close() # close the file 
    return text 

try: 
    text = open_file() # open file and write it into var 
    except FileNotFoundError: 
     print("File was not found!") 
     text = "" # if FileNotFoundError = True -> text = none 

    lower_text = text.lower() # transform txt into lower cases 
    text_with_out_special_signs = re.findall(r'[a-z]*', lower_text) #delete signs like =,#,! 

    counts_of_words = Counter(text_with_out_special_signs) # transform list in Counter 

    for x in counts_of_words.most_common(): # show results 
     print(x) 
+1

インデントあなたのコードを。 – MYGz

+0

pointer: 'with'を使って開いたファイルを' f.close'する必要はありません。全体のポイントは、自動的に閉じられることです。それ以外に、あなたの質問は何ですか? –

+0

're.findall'を使用しているため、これは動作しません –

答えて

1

あなたはこのような何かを行うことができます:適切

text_more_than_3_char_words = [w for w in text_with_out_special_signs if len(w) > 2] 
counts_of_words = Counter(text_more_than_3_char_words) # transform list in Counter 
+0

ありがとうございます!それは私が望むような仕事です。 – Just4Fun

関連する問題