4

「こんにちは、こんにちは」などの文字列を変換して辞書に変換し、この辞書を使用して、辞書内の各単語の数を数え、アルファベットで返したいと思っています。注文。したがって、この場合は次のように返されます。

[('hello', 1), ('hi', 1), ('there', 2)]

任意の助けをいただければ幸いです

4

2 に答える 2

14
>>> from collections import Counter
>>> text = "hello there hi there"
>>> sorted(Counter(text.split()).items())
[('hello', 1), ('hi', 1), ('there', 2)]

class collections.Counter([iterable-or-mapping])

ACounterは、dictハッシュ可能なオブジェクトをカウントするためのサブクラスです。これは、要素がディクショナリ キーとして格納され、そのカウントがディクショナリ値として格納される順序付けられていないコレクションです。カウントは、ゼロまたは負のカウントを含む任意の整数値にすることができます。このCounterクラスは、他の言語のバッグまたはマルチセットに似ています。

于 2013-05-15T06:01:52.490 に答える
4

ジャムラックはうまくいきましたCounter。これはインポートなしのソリューションCounterです:

text = "hello there hi there"
dic = dict()
for w in text.split():
    if w in dic.keys():
        dic[w] = dic[w]+1
    else:
        dic[w] = 1

与える

>>> dic
{'hi': 1, 'there': 2, 'hello': 1}
于 2013-05-15T06:25:42.187 に答える