【发布时间】:2019-09-26 04:21:48
【问题描述】:
假设我有以下列表。
food_list = ['ice cream', 'apple', 'pancake', 'sushi']
我想在以下字符串中找到该列表中的每个项目。
my_str = 'I had pancake for breakfast this morning, while my sister ate some apples. I brought one apple and ate it on my way to work. My coworker was having his birthday today, and he gave us free ice cream. It was the best ice cream I had this year.'
my_str = my_str.lower()
我要统计字符串中的项数。
ice cream : 2, apple: 1, pancake: 1, sushi:0
注意苹果只计算一次,因为apples 不应该被计算在内。由于ice cream 之类的项目,我不可能将其按空间拆分。
我正在考虑用一些东西替换列表中的单词并稍后计算,但它非常慢(当应用于更大的数据时)。我想知道是否有更好的解决方案。
for word in food_list:
find_word = re.sub(r'\b'+word+r'\b', "***", my_str)
count_word = find_word.count("***")
print(word+": "+str(count_word))
我希望它足够清楚。谢谢
【问题讨论】: