Python統計文字列の単語ごとの出現回数

846 ワード

統計文字列の各単語の数
特定の文字列が指定されていると仮定します.たとえば、.等記号、どのように各単語の個数を統計しますか?
3つの方法があり、3つの方法の最初のステップは文字列を単語リストに切断することであり、異なる点は後の処理である.以下、
この3つの方法を実証します.
1つ目:
  • from collections import Counter
    sentence='i think i can jump you can not jump'
    counts=Counter(sentence.split())
    print(counts)
    この方式はcollectionsクラスライブラリのCountメソッド
  • を用いる.
  • 第2の方式:
  • result={word:sentence.split().count(word) for word in set(sentence.split())}
    print(result)
    #    ,      ,      

     
  • 第3の態様
  • def counts(sentence):
        words=sentence.split()
        dict_words={}
        for i in words:
            if i not in dict_words.keys():
                 dict_words[i]=1
            else:
                dict_words[i] += 1
        return dict_words
    print(counts(sentence))
    #