问题描述
我想知道在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