我有一个包含几个观察结果的文本文件。每个观察都在一行中。我想检测一行中每个单词的唯一出现。换句话说,如果同一个词在同一行出现两次或多次,它仍然算作一次。但是,我想计算所有观察中每个单词的出现频率。这意味着如果一个单词出现在两行或多行中,我想计算它出现的行数。这是我编写的程序,它在处理大量文件时真的很慢。我还通过引用另一个文件来删除文件中的某些单词。请提供有关如何提高速度的建议。谢谢你。
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")