计算文本中字符串列表的出现次数

时间:2020-04-10 10:27:20

标签: python nltk

我想用Python计算文本中列表元素的出现次数。我知道我可以使用.count(),但是我已经读到这会影响性能。另外,列表中的元素可以包含1个以上的单词。

my_list = ["largest", "biggest", "greatest", "the best"]

my_text = "i have the biggest house and the biggest car. My friend is the best. Best way win this is to make the largest house and largest treehouse and then you will be the greatest"

我可以这样做:

num = 0
for i in my_list:
   num += my_text.lower().count(i.lower())

print(num)

这种方法有效,但是如果我的列表包含500个元素并且我的字符串是3000个单词,那么在这种情况下,我的性能将非常低。

有没有办法做到这一点,但性能好/快?

1 个答案:

答案 0 :(得分:2)

由于my_list包含一个以上单词的字符串,因此您必须在my_text的{​​{3}}中查找匹配项,因为空格分割不会进行。还要注意,您的方法不建议使用,因为对于my_list中的每个单个字符串,您都将使用my_text遍历整个字符串count。更好的方法是预先定义要查找的n-grams

这是使用nltk的{​​{1}}的一种方法。 我在ngram中添加了另一个字符串以更好地说明该过程:

my_list

第一步是定义一个包含不同长度的n-gram的字典:

from nltk import ngrams
from collections import Counter, defaultdict

my_list = ["largest", "biggest", "greatest", "the best", 'My friend is the best']
my_text = "i have the biggest house and the biggest car. My friend is the best. Best way win this is to make the largest house and largest treehouse and then you will be the greatest"

然后将d = defaultdict(list) for i in my_list: k = i.split() d[len(k)].append(tuple(k)) print(d) defaultdict(list, {1: [('largest',), ('biggest',), ('greatest',)], 2: [('the', 'best')], 5: [('My', 'friend', 'is', 'the', 'best')]}) 拆分为一个列表,并为my_text中的每个键找到对应的d并从结果中构建一个n-grams。然后针对Counter中该特定键中的每个值,使用d中的计数进行更新:

Counter

哪个会给:

my_text_split = my_text.replace('.', '').split()
match_counts = dict()
for n,v in d.items():
    c = Counter(ngrams(my_text_split, n))
    for k in v:   
        if k in c:
            match_counts[k] = c[k] 
相关问题