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

时间:2013-05-10 17:19:55

标签: python string count

我有以下情况:

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脚本。

3 个答案:

答案 0 :(得分:3)

>>> s = 'this is the string that Luci want to parse for a dataset uci at web'
>>> s.split(' ').count('uci')
1

答案 1 :(得分: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))

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

count = re.split(r'\W', string).count('uci')

这两种方法都返回1

答案 2 :(得分: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}
相关问题