Python: 寻找文本中单词列表的最佳/高效方法是什么?
我有大约300个单词的列表,还有一大堆文本,我想扫描这些文本,看看每个单词出现了多少次。
我正在使用Python的re模块来实现这个功能:
for word in list_word:
search = re.compile(r"""(\s|,)(%s).?(\s|,|\.|\))""" % word)
occurrences = search.subn("", text)[1]
不过,我想知道有没有更高效或者更优雅的方法来做到这一点?
8 个回答
0
听起来自然语言工具包(Natural Language Toolkit)可能正好符合你的需求。
1
试着把你文本中的所有标点符号去掉,然后再根据空格来分割。接着你只需要这样做:
for word in list_word:
occurence = strippedText.count(word)
或者如果你用的是Python 3.0,我觉得你可以这样做:
occurences = {word: strippedText.count(word) for word in list_word}
5
如果你有很多很多的文字,我建议不要用正则表达式来处理这些文字,而是直接把文字分开:
words = {"this": 0, "that": 0}
for w in text.split():
if w in words:
words[w] += 1
这样你就可以得到每个单词出现的频率了。