gpt4 book ai didi

python - 如何在python中找到另一个字符串(句子)中一个字符串(可以是多个单词)的计数/出现次数

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:19 26 4
gpt4 key购买 nike

我必须计算一个字符串(可以是 1 个或多个单词)在另一个字符串(一个句子)中的出现次数,并且不应该区分大小写。

例如-

a = "Hi my name is Alex and hi to you as well. How high is the building? The highest floor is 18th. Highlights .... She said hi as well. Do you know highlights of the match ... hi."

b = "hi" #word/sentence to find count of

我试过了-

a.lower().count(b) 

返回

>> 8 

而要求的答案应该是

>> 4.

对于多词,此方法似乎有效,但我不确定限制情况。我怎样才能解决这个问题?

最佳答案

您可以使用 re.findall搜索具有前导和尾随单词边界的子字符串:

import re

print(len(re.findall(r'\b{}\b'.format(b), a, re.I))) # -> 4
# ^ ^
# |___|_ word boundaries ^
# |_ case insensitive match

关于python - 如何在python中找到另一个字符串(句子)中一个字符串(可以是多个单词)的计数/出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185093/

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