Python 计算字符串中的子字符串或字
我想知道,在python中,如何计算字符串中单词“the”的出现次数。 我遇到的问题是,它会用诸如:there,theatre…等词来计算“The”Python 计算字符串中的子字符串或字,python,string,count,Python,String,Count,我想知道,在python中,如何计算字符串中单词“the”的出现次数。 我遇到的问题是,它会用诸如:there,theatre…等词来计算“The” 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
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))
很抱歉,如果我的格式设置不正确,这是我的第一篇文章。您可以尝试在
\b
上以不区分大小写的模式进行正则表达式搜索,它将查找文本中的所有单词:
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
您可以尝试在\b\b
上以不区分大小写的模式进行正则表达式搜索,该搜索将查找文本中的所有单词:
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
别忘了导入re
:)@pitamer。别忘了导入re
:)@pitamer。