简体   繁体   English

在Python中计算相等的字符串

[英]Counting equal strings in Python

I have a list of strings and some of them are equal. 我有一个字符串列表,其中一些是相同的。 I need some script which would count equal strings. 我需要一些可以计算相同字符串的脚本。 Ex: 例如:

I have a list with some words : 我有一个单词列表:

"House" “屋”
"Dream" “梦想”
"Tree" “树”
"Tree" “树”
"House" “屋”
"Sky" “天空”
"House" “屋”

And the output should look like this: 输出应该如下所示:

"House" - 3 “众议院” - 3
"Tree" - 2 “树” - 2
"Dream" - 1 “梦想” - 1
and so on 等等

Use collections.Counter() . 使用collections.Counter() It is designed for exactly this use case: 它专为这个用例而设计:

>>> 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

Solution

This is quite simple ( words is a list of words you want to process): 这很简单( words是您要处理的单词列表):

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

It does not require any additional modules. 它不需要任何额外的模块。

Test 测试

For the following words value: 对于以下words值:

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

it will give you the following result: 它会给你以下结果:

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

Does it answer your question? 它能回答你的问题吗?

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)

I will extend Tadeck's answer to print the results. 我将扩展Tadeck的答案来打印结果。

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

Below code should get you as expected 下面的代码可以让你按预期方式

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