Python .count字符串函数-计算字符串或行中出现的确切单词

时间:2019-05-27 20:02:26

标签: python python-3.x string count

我想计算字符串中单词的出现次数。但我只想计算确切的发生次数,而不是从子字符串开始计算。

例如如果我要计数的字符串是->“这很好”,并且如果我要计数出现的单词是“是”,则我只想得到出现的是1而不是2。但是我的代码计数“是“来自” This“一词。我怎样才能做到这一点。对不起,我英语不好。

                                    [0] file_a.py                                    
                                    [0] file_b.py                                    
                                    [1] file_d.py                                    
                                    [1] file_c.py                                    

text = "This is good"
text.count("is")

>>> 2

3 个答案:

答案 0 :(得分:2)

如果要使用此方法,则只需插入空格(如果您始终要搜索单词)

text = "This is good"
print (text.count(" is"))

输出:

1

更好的解决方案将是:

text = "This is good"
num = text.split().count('is')
print (num)

输出:

1

使此计数器不区分大小写,例如在这种情况下:

text = "Is this ok, it is just example is"
num = text.lower().split().count('is')
print (num)

输出:

3

  

lower()方法返回字符串的副本,其中所有   基于大小写的字符已小写。

     

语法:

str.lower()
     

split()方法将字符串拆分为列表。

     

您可以指定分隔符,默认分隔符是任何空格。

     

注:指定max时,列表将包含指定的   元素数量加一。

     

语法:

string.split(separator, max)

答案 1 :(得分:0)

您首先必须通过将字符串用空格分开来获得单个单词:

words = text.split()

现在将单词等于您要检查的字符串的列表中的所有项目相加:

sum(char for char in words if char == string_to_check)

在一个函数中,您将获得以下信息:

def count(string, check):
    return sum(char for char in string.split() if char == check)

答案 2 :(得分:0)

您可以使用正则表达式,它将帮助您找到被任何单词边界分隔的子字符串:

import re

text = "This is good is\tis\t"
occurences = sum(1 for _ in re.finditer(r"\bis\b", text))