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

问题描述 投票:0回答:1

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

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个单词,那么在那种情况下,我的性能就会非常低。

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

python nltk
1个回答
2
投票

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

这里是使用n-gramsnltk的一种方法。我在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] 
© www.soinside.com 2019 - 2024. All rights reserved.