いくつかの観察結果を含むテキスト ファイルがあります。各観測値は 1 行に表示されます。行内の各単語の一意の出現を検出したいと思います。つまり、同じ単語が同じ行に 2 回以上出現しても、1 回としてカウントされます。ただし、すべての観察で各単語の出現頻度を数えたいと思います。これは、ある単語が 2 行以上にまたがって出現する場合、その単語が出現した行数を数えたいということです。これが私が書いたプログラムで、多数のファイルの処理が非常に遅いです。また、別のファイルを参照して、ファイル内の特定の単語を削除します。速度を改善する方法についての提案を提供してください。ありがとうございました。
import re, string
from itertools import chain, tee, izip
from collections import defaultdict
def count_words(in_file="",del_file="",out_file=""):
d_list = re.split('\n', file(del_file).read().lower())
d_list = [x.strip(' ') for x in d_list]
dict2={}
f1 = open(in_file,'r')
lines = map(string.strip,map(str.lower,f1.readlines()))
for line in lines:
dict1={}
new_list = []
for char in line:
new_list.append(re.sub(r'[0-9#$?*_><@\(\)&;:,.!-+%=\[\]\-\/\^]', "_", char))
s=''.join(new_list)
for word in d_list:
s = s.replace(word,"")
for word in s.split():
try:
dict1[word]=1
except:
dict1[word]=1
for word in dict1.keys():
try:
dict2[word] += 1
except:
dict2[word] = 1
freq_list = dict2.items()
freq_list.sort()
f1.close()
word_count_handle = open(out_file,'w+')
for word, freq in freq_list:
print>>word_count_handle,word, freq
word_count_handle.close()
return dict2
dict = count_words("in_file.txt","delete_words.txt","out_file.txt")