1

strcount(S)単語をキーとして辞書を返し、単語が対応する値として出現する回数を返す関数を作成するのに助けが必要です。出力は次のようになります。

strcount("a a a a b b")
{'a': 4, 'b': 2}
strcount("one")
{'one': 1}
sorted(strcount("this one and that one for one time").items())
[('and', 1), ('for', 1), ('one', 3), ('that', 1), ('this', 1), ('time', 1)]
4

4 に答える 4

3

最も Pythonic なソリューションは、次を使用することcollections.Counterです。

>>> from collections import Counter
>>> Counter("this one and that one for one time".split()).items()
[('and', 1), ('for', 1), ('that', 1), ('this', 1), ('one', 3), ('time', 1)]

独自のソリューションを作成する場合は、次のようにします。

  1. 文字列を単語のリストに分割します。これに使えます.split()
  2. 各キーが 1 つの単語で、値が である辞書を作成します0
  3. 単語のリストを繰り返します。すべての単語について、 に追加1your_dict[word]ます。
于 2012-10-02T03:25:05.030 に答える
0

を使用した@Blenderの回答Counterは素晴らしいですが、Pythonバージョン2.7以降用です。

Python の下位バージョンで機能する代替ソリューションを次に示します。

from collections import defaultdict

word_freq = defaultdict(int)
for i in "this one and that one for this one".split():
   word_freq[i] += 1

これにより、次のことが得られます。

>>> word_freq
defaultdict(<type 'int'>, {'this': 2, 'and': 1, 'that': 1, 'for': 1, 'one': 3})
>>> word_freq['one']
3
于 2012-10-02T04:15:17.240 に答える