Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算字符串中的子字符串或字_Python_String_Count - Fatal编程技术网

Python 计算字符串中的子字符串或字

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

我想知道,在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 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。