计算字符串中的子字符串或单词

问题描述

我想知道在python中如何计算字符串中“ the”的出现。 我得到的问题是,它将用“ the”这样的词来计数:there,theatre .... etc

s = "The Journey: today I went there! There was not the...theatre but the Walgreens so I could buy a thermometer"

howmanythe = s.count("the") #I feel like here you could do " the " but I would miss any "the" after grammar notation
print("There are {} many the's in that phrase".format(howmanythe))

对不起,如果我的格式不正确,这是我的第一篇文章。

解决方法

在不区分大小写的模式下,您可以尝试在\bthe\b上进行正则表达式搜索,该模式将在文本中找到所有the个单词:

s = "The Journey: today I went there! There was not the...theatre but the Walgreens so I could buy a thermometer"
num = len(re.findall(r'\bthe\b',s,flags=re.IGNORECASE))
print("There were " + str(num) + " 'the' words in the text")

此打印:

There were 3 'the' words in the text

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...