在字符串中查找特定单词,Python
创建一个函数,这个函数接收两个参数:一个是文本(以字符串形式),另一个是一个单词集合(也是字符串)。这个函数的作用是返回在这个文本中出现的单词集合里的单词数量。
比如说,调用 count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) 会返回 3,因为在文本中有 "how"、"are" 和 "you" 这三个单词。
我尝试过:
import re
def count_words(text, words):
count = 0
for i in words:
x = re.compile('.*'+i+'.*')
if x.search(text):
count +=1
return count
我想这个问题之前应该已经被回答过很多次了,但我就是找不到相关的答案,所以很抱歉。如果能得到任何帮助,我将非常感激,谢谢!
1 个回答
8
def count_words(text, words):
answer = 0
for i in range(len(text)):
if any(text[i:].startswith(word) for word in words):
answer += 1
return answer
如果你想让它对文本中的字母大小写不敏感:
def count_words(text, words):
text = text.lower()
answer = 0
for i in range(len(text)):
if any(text[i:].startswith(word) for word in words):
answer += 1
return answer
当然,这可以用一句话就搞定:
sum(text.count(word) for word in words)