count String函数从字符串或lin中精确计算单词的出现次数

2024-06-02 05:19:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,如果我要计算的字符串是->这是好的,如果我想计算出现的单词是“is”,我只想得到出现的是1而不是2。但是我的代码从“This”单词计算“is”。我该怎么做。对不起,我的英语不好

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

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

>>> 1

Tags: 字符串代码textgtiscountthis单词
3条回答

如果你想使用这个方法,你可以插入空格(如果你总是在搜索单词)

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)

输出:

The method lower() returns a copy of the string in which all case-based characters have been lowercased.

Syntax:

str.lower()

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When max is specified, the list will contain the specified number of elements plus one.

Syntax:

string.split(separator, max)

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

import re

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

首先必须通过将字符串按空格拆分来获取单个单词:

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)

相关问题 更多 >