我如何计算确切的单词?

时间:2019-06-15 07:56:08

标签: python count

例如,我有这样的代码

string = "abito to doto moto" 
print(string.count("to"))

我只希望结果为1,但在其他三个结果中也总是计为“至”。

4 个答案:

答案 0 :(得分:2)

您可以通过以下方式使用正则表达式(re模块):

import re
string = "abito to doto moto"
occurences = len(re.findall(r'\bto\b',string))
print(occurences)

输出:

1

说明: \bre.findall的第一个参数中具有特殊含义,即单词边界-表示在to之前需要以字符串或标点符号(包括空格)开头,并且以字符串或或标点符号结尾( (包括空格)在to之后。 因此,对于等于abito to, doto motoabito to: doto moto的字符串,我的代码也将给出1,依此类推。

答案 1 :(得分:0)

我对“ to”的第一个和最后一个出现感到厌恶。您可以根据需要在for循环中更改条件。

li = list(string.split(" ")) 
count = 0;
for i in range(1,len(li)-1):
    if li[i]== "to":
        count= count + 1
print(count)

答案 2 :(得分:0)

string.count(" to ")仅在"to"后没有特殊字符

有效

这是一些示例:

    >>> string = 'abito to doto moto to.'
    >>> string.count("to")
    5
    >>> string.count(" to ")
    1
    >>> string.split().count("to")
    1
    >>> string.split(" ").count("to")
    2
    >>> import re
    >>> sum(1 for _ in re.finditer(r'\b%s\b' % re.escape("to"), string))
    2

编辑:感谢@Grzegorz Krug的建议编辑,使用正则表达式时,结果为 2 (由于我的string与@Jess示例不同)

how_many = len(re.findall('\Wto\W', string)) # '\W' is to avoid word symbols a-zA-Z and _

答案 3 :(得分:0)

您必须在此字符串'to'->'to'中添加空格,我不建议这样做。因为看起来您想查找单词“ to”,并且如果字符串从“ to”开始,则添加空格可能会失败

string = "abito to doto moto" 
words = string.split()
print(words.count("to"))