我写了一个简单的程序来分析Python中的.txt文件。
我构建的用于分析的功能,以及为输入文本文件找到某些单词的频率'添加作为较大单词的一部分的短单词,例如(' not',#39; note'),以便结果不正确。
def apply_all(self):
with open(self.fname, 'r') as f:
words = f.read()
filtered = "".join(filter(lambda x: x not in '".,;:!?–-', words))
word = []
word_list = []
for i in filtered.split():
word.append(i)
word_list.append(words.count(i))
b = dict(zip(word, word_list))
aux = [(b[key], key) for key in b]
aux.sort()
aux.reverse()
print('Pairs', aux)
这个问题有什么简单的解决方案,还是我必须通过多个查询来纠正输出?
答案 0 :(得分:0)
根据文档words.count(i)
返回子字符串的出现次数,因此在not
时会计算note
和i=not
。修复此问题的最简单方法是在不偏离原始代码的情况下,拆分输入并在名为count
的结果列表中调用individual_words
。
请注意,我已将文字输入转换为小写,否则The
和the
被视为单次出现。
words = "The not so quick brown dog jumps over the lazy dog eating his bone"
filtered = "".join(filter(lambda x: x not in '".,;:!?–-', words)).lower()
word = []
word_list = []
individual_words = filtered.split()
for i in individual_words:
word.append(i)
word_list.append(individual_words.count(i))
b = dict(zip(word, word_list))
aux = [(b[key], key) for key in b]
aux.sort()
aux.reverse()
print('Pairs', aux)
这给出了以下输出:
Pairs [(2, 'the'), (2, 'dog'), (1, 'so'), (1, 'quick'), (1, 'over'), (1, 'not'), (1, 'lazy'), (1, 'jumps'), (1, 'his'), (1, 'eating'), (1, 'brown'), (1, 'bone')]