gpt4 book ai didi

python - 在字符串中查找特定单词,Python

转载 作者:行者123 更新时间:2023-11-28 20:22:02 26 4
gpt4 key购买 nike

创建一个函数,给定两个参数:作为字符串的文本和作为一组字符串的单词,返回字符串中包含的单词数。

例如。 count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3

我的尝试:

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

我想这个问题之前已经回答过好几次了,但我就是找不到相关的答案,所以我很抱歉。任何帮助将不胜感激,谢谢

最佳答案

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)

关于python - 在字符串中查找特定单词,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25235215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com