python - 如何更快地计算 nltk plaintextcorpus 中的单词?

标签 python nlp nltk corpus

我有一组文档,我想返回一个元组列表,其中每个元组都有给定文档的日期和给定搜索词在该文档中出现的次数。我的代码(如下)有效,但速度很慢,而且我是一个 n00b。有明显的方法可以使它更快吗?任何帮助将不胜感激,主要是为了让我可以学习更好的编码,同时也可以让我更快地完成这个项目!

def searchText(searchword):
    counts = []
    corpus_root = 'some_dir'
    wordlists = PlaintextCorpusReader(corpus_root, '.*')
    for id in wordlists.fileids():
        date = id[4:12]
        month = date[-4:-2]
        day = date[-2:]
        year = date[:4]
        raw = wordlists.raw(id)
        tokens = nltk.word_tokenize(raw)
        text = nltk.Text(tokens)
        count = text.count(searchword)
        counts.append((month, day, year, count))

    return counts

最佳答案

如果你只是想要一个词频统计,那么你不需要创建nltk.Text对象,甚至不需要使用nltk.PlainTextReader。相反,直接转到 nltk.FreqDist

files = list_of_files
fd = nltk.FreqDist()
for file in files:
    with open(file) as f:
        for sent in nltk.sent_tokenize(f.lower()):
            for word in nltk.word_tokenize(sent):
                fd.inc(word)

或者,如果您不想进行任何分析 - 只需使用 dict

files = list_of_files
fd = {}
for file in files:
    with open(file) as f:
        for sent in nltk.sent_tokenize(f.lower()):
            for word in nltk.word_tokenize(sent):
                try:
                    fd[word] = fd[word]+1
                except KeyError:
                    fd[word] = 1

这些可以通过生成器表达式变得更加高效,但我使用 for 循环是为了提高可读性。

关于python - 如何更快地计算 nltk plaintextcorpus 中的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3902044/

相关文章:

python - 从关键字生成句子。每个关键字都有相关单词包

python - 查找错误 : Resource 'corpora/stopwords' not found

Python 如何通过上下文管理器强制对象实例化?

python - scikit learn 模型的嵌套并行性

python - lstm 之后的 TimeDistributed(Dense()) 与 Dense()

java - 使用 Clear 解析器进行语义角色标记

python - 使用 PlainTextCorpusReader 创建语料库并进行分析

python - 如何在 python 中将文本 block 标记为一个标记?

python - 如何为霍夫曼编码和解码创建一棵树?

python - 如何将一列保留为数据框