pandas 计数String Python中列表项的出现次数[duplicate]

rbl8hiat  于 2023-01-15  发布在  Python
关注(0)|答案(3)|浏览(99)
    • 此问题在此处已有答案**:

(29个答案)
20小时前关门了。
我正在努力实现这一目标

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"
some_function(string_list,text)

Output: [1,2,1]

我该如何实现呢?得到一个将所有出现次数相加的数字(本例中为4)是没有问题的,但我希望它被string_list项分隔开。

5us2dqdw

5us2dqdw1#

return [text.count(string) for string in string_list]
hs1rzwqc

hs1rzwqc2#

下面是一个很长的方法:

from collections import defaultdict

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"

def count_occurrences(string_list, text):
    counts = defaultdict(int)
    for string in text.split():
        if string in string_list:
            counts[string] += 1
    return counts.values()

print(count_occurrences(string_list, text))

dict_values([1, 2, 1])
relj7zay

relj7zay3#

你可以使用count()函数来计算字符串中的子字符串。下面的代码可能会有所帮助

def get_count(slist,text):
    result=[]
    for string in slist:
        result.append(text.count(string))
    return result
    

string_list = ["red","blue","green"]
text = "This is a string about my favourite colours like red blue and green but blue is the best"

print(get_count(string_list,text))

输出

[1, 2, 1]

相关问题