计算字符串中出现的单词数

2024-04-23 20:40:00 发布

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

我有以下情况:

str='this is the string that Luci want to parse for a dataset uci at web'
word='uci'

str.count(word)=?

我只想计算独立出现的“uci”(不在任何单词内) 所以输出应该是1而不是2!在

需要Python脚本。在


Tags: thetoforstringthatparseis情况
3条回答
>>> s = 'this is the string that Luci want to parse for a dataset uci at web'
>>> s.split(' ').count('uci')
1
 def count_words(str):
   words = str.split()
   counts = {}
   for word in words:
    if word in counts:
     counts[word] = counts[word] + 1
    else:
     counts[word] = 1
   return counts

count_words(str)
{'a': 1, 'web': 1, 'string': 1, 'for': 1, 'that': 1, 'this': 1, 'is': 1, 'dataset': 1, 'parse': 1, 'to': 1, 'at': 1, 'want': 1, 'the': 1, 'Luci': 1, 'uci': 1}

在不提供太多信息的情况下,可以使用re来查找模式。尤其是,你可能会寻找“uci”,周围有单词障碍:

string = 'this is the string that Luci want to parse for a dataset uci at web'
count = len(re.findall(r'[^\W]uci[\W$]', string))

或者,您可以拆分非单词字符并计算出现的次数:

^{pr2}$

这两种方法都返回1

相关问题 更多 >