繁体   English   中英

在Python中计算相等的字符串

[英]Counting equal strings in Python

我有一个字符串列表,其中一些是相同的。 我需要一些可以计算相同字符串的脚本。 例如:

我有一个单词列表:

“屋”
“梦想”
“树”
“树”
“屋”
“天空”
“屋”

输出应该如下所示:

“众议院” - 3
“树” - 2
“梦想” - 1
等等

使用collections.Counter() 它专为这个用例而设计:

>>> import collections
>>> seq = ["House", "Dream", "Tree", "Tree", "House", "Sky", "House"]
>>> for word, cnt in collections.Counter(seq).most_common():
        print repr(word), '-', cnt

'House' - 3
'Tree' - 2
'Sky' - 1
'Dream' - 1

这很简单( words是您要处理的单词列表):

result = {}
for word in set(words):
    result[word] = words.count(word)

它不需要任何额外的模块。

测试

对于以下words值:

words = ['House', 'Dream', 'Tree', 'Tree', 'House', 'Sky', 'House']

它会给你以下结果:

>>> result
{'Dream': 1, 'House': 3, 'Sky': 1, 'Tree': 2}

它能回答你的问题吗?

from collections import defaultdict
counts = defaultdict(int)
for s in strings:
    counts[s] += 1
for (k, v) in counts.items():
    print '"%s" - %d' % (k, v)

我将扩展Tadeck的答案来打印结果。

for word in set(words):
  print '''"%s" - %d''' %(word, words.count(word))

下面的代码可以让你按预期方式

stringvalues = ['House', 'Home', 'House', 'House', 'Home']
for str in stringvalues:
    if( str in newdict ):
        newdict[str] = newdict[str] + 1
    else:
        newdict[str] = 1
all = newdict.items()
for k,v in all:
    print "%s-%s" % (k,v)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM