gpt4 book ai didi

python - 如何在Python中使用NLTK有效地查找字母列表的出现次数?

转载 作者:行者123 更新时间:2023-12-01 06:00:51 24 4
gpt4 key购买 nike

我可以使用 NLTK python2.6 读取文本语料库:

from nltk.corpus import gutenberg
for fileid in gutenberg.fileids():
num_chars = len(gutenberg.raw(fileid))
num_words = len(gutenberg.words(fileid))
num_sents = len(gutenberg.sents(fileid))
num_vocab = len(set([w.lower() for w in gutenberg.words(fileid)]))
print int(num_chars/num_words), int(num_words/num_sents), int(num_words/num_vocab), fileid

现在我想按单词和句子查找字母的平均出现次数,例如 num_letters(whole_text, ['a', 'bb', 'ccc'])。预期输出为:

a = n11/n12,bb = n21/n22,ccc = n31/n32

其中 n11 = 单词中的出现次数,n12 = 句子中的出现次数。

最佳答案

您可以通过使用正则表达式在大量文本中查找要匹配的每个元素的所有匹配项来实现此目的:

import re
matches = ['a', 'bb', 'ccc', 'and']

#add this line into your for loop:
num_letter_dict = dict([(match, len([seq.start() for seq in
re.finditer(match, gutenberg.raw(fileid))])) for match in matches])

这将创建一个包含所有匹配项及其频率的字典。因此,对于第一个文本 austen-emma.txt,我们得到 num_letter_dict:

{'a': 53669, 'and': 5257, 'ccc': 0, 'bb': 52}

要从这里得出单词和句子的平均出现次数很简单,只需分别除以 num_wordsnum_sents 即可。

要查找包含这些元素的单词数(不计算单词内的重复次数),请使用:

num_letter_in_words = dict([(match, len([word for word in gutenberg.words(fileid)
if match in word])) for match in matches])
#from the same text gives:
{'a': 50043, 'and': 5257, 'ccc': 0, 'bb': 52}

举个例子:

text = 'apples pairs bannanas'
matches = ['a', 'n', 'p']
#gives:
{'a': 3, 'p': 2, 'n': 1}

关于python - 如何在Python中使用NLTK有效地查找字母列表的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com