我知道我可以在字符串中找到一个单词
if word in my_string:
但我想在字符串中找到所有“单词”,就像这样。
counter = 0
while True:
if word in my_string:
counter += 1
如果不一遍又一遍地“计算”同一个词,我怎样才能做到这一点?
请您参考如下方法:
如果你想确保它计算一个完整的单词,比如 is 将只有一个在 this is 中,即使有一个 is 在 this 中,您可以拆分、过滤和计数:
>>> s = 'this is a sentences that has is and is and is (4)'
>>> word = 'is'
>>> counter = len([x for x in s.split() if x == word])
>>> counter
4
但是,如果您只想计算子字符串的所有出现次数,即 is 也将匹配 is in this 那么:
>>> s = 'is this is'
>>> counter = len(s.split(word))-1
>>> counter
3
换句话说,拆分 每次出现该单词的字符串,然后减去一个以得到计数。
编辑 - 仅使用计数:
这是漫长的一天所以我完全忘记了但是 str 有一个内置的方法用于这个 str.count(substring) 和我的第二个答案一样但更具可读性。请考虑使用此方法(并查看其他人的答案以了解如何使用)
