-4

我有以下情况:

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

4

3 回答 3

3
>>> s = 'this is the string that Luci want to parse for a dataset uci at web'
>>> s.split(' ').count('uci')
1
于 2013-05-10T17:28:27.027 回答
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

于 2013-05-10T17:29:53.687 回答
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}
于 2013-05-10T17:30:27.710 回答