Counting word frequency and making a dictionary from it

前端 未结 10 954
南旧
南旧 2020-12-05 21:08

I want to take every word from a text file, and count the word frequency in a dictionary.

Example: \'this is the textfile, and it is used to take words and co

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 21:36

    from collections import Counter
    t = 'this is the textfile, and it is used to take words and count'
    
    dict(Counter(t.split()))
    >>> {'and': 2, 'is': 2, 'count': 1, 'used': 1, 'this': 1, 'it': 1, 'to': 1, 'take': 1, 'words': 1, 'the': 1, 'textfile,': 1}
    

    Or better with removing punctuation before counting:

    dict(Counter(t.replace(',', '').replace('.', '').split()))
    >>> {'and': 2, 'is': 2, 'count': 1, 'used': 1, 'this': 1, 'it': 1, 'to': 1, 'take': 1, 'words': 1, 'the': 1, 'textfile': 1}
    

提交回复
热议问题