Created
August 28, 2017 05:58
-
-
Save monchy-monchy/a7cb2b1f8afdea4f78b42635ddcc121e to your computer and use it in GitHub Desktop.
テキストファイルで使用されている英単語の数をカウントする。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# モジュールのインポート | |
import os | |
import re | |
# 単語を格納するための空のリスト(単語リスト)を作成 | |
pre_words = [] | |
words = [] | |
# テキストファイルかどうかをチェックする機能の実装。 | |
# 対象となるファイルが .txt ならTrue、それ以外なら Falseを返す。 | |
def text_checker(name): | |
text_regex = re.compile(r'.+\.txt') | |
if text_regex.search(str(name)): | |
return True | |
else: | |
return False | |
# テキストファイルの文字列を単語に分割してリスト化する機能の実装。 | |
def word_list(text): | |
f = open(text) | |
data = f.read() | |
# 空白文字列で区切る。 | |
for word in data.split(): | |
pre_words.append(word) | |
# wordsに単語を格納していく機能の実装。 | |
# 対象フォルダのファイルを順番に開いていき、txtファイルの判定→単語リストの格納を実行する。 | |
# txtファイル以外は pass する。 | |
for file in os.listdir(os.getcwd()): | |
if text_checker(file): | |
word_list(file) | |
else: | |
pass | |
for lw in pre_words: | |
lower_word = lw.lower() | |
words.append(lower_word) | |
# 単語リストに格納されたデータから、各単語の使用回数を計算し、使用回数の多い順にならべかえる。 | |
# 単語の使用頻度を取りまとめる空の辞書を作成。 | |
# キーが単語、値が回数 | |
word_counter = {} | |
for w in words: | |
word_counter.setdefault(w, 0) | |
word_counter[w] = word_counter[w] + 1 | |
# word_counter は辞書形式でソートができないため、リスト形式に変更し、使用回数順でソートする。 | |
word_counter_listed = [(v, k) for k, v in word_counter.items()] | |
word_counter_listed.sort() | |
word_counter_listed.reverse() | |
# 参考までに、word_counterlisted の内容を全てoutputしてみる。 | |
# 500単語ごとに区切りを入れる。 | |
all_word_list = open('AllWordList.txt', 'w') | |
for i in range(len(word_counter_listed)): | |
if i % 500 == 0: | |
all_word_list.write('------------' + str(i) + '------------\n') | |
all_word_list.write(str(word_counter_listed[i])+'\n') | |
all_word_list.close() | |
# word_counter_listed から、上位1000件を抽出し、 top_use リストにまとめる。 | |
top_use = [] | |
for count in word_counter_listed[:1000]: | |
top_use.append(count) | |
# top_use リストの結果をtxtファイルに書き出す。 | |
# frequency_word_list.txt の作成。 | |
frequency_word_list = open('frequency_word_list.txt', 'w') | |
# 単語のみを抽出しやすいように、top_use をリスト→辞書に変換 | |
top_use_dict = dict(top_use) | |
# top_use_dictから値(単語)のみを抽出する。 | |
top_use_list = list(top_use_dict.values()) | |
# top_use_listの単語をfor文でfrequency_word_listに書き込んでいく。 | |
# 単語ごとに改行するように、 \nを単語の末尾に付加する。 | |
for i in range(len(top_use_list)): | |
frequency_word_list.write(str(top_use_list[i]) + ' ' + '\n') | |
frequency_word_list.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment