Counting word frequency and making a dictionary from it

前端 未结 10 955
南旧
南旧 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:29

    The following takes the string, splits it into a list with split(), for loops the list and counts the frequency of each item in the sentence with Python's count function count (). The words,i, and its frequency are placed as tuples in an empty list, ls, and then converted into key and value pairs with dict().

    sentence = 'this is the textfile, and it is used to take words and count'.split()
    ls = []  
    for i in sentence:
    
        word_count = sentence.count(i)  # Pythons count function, count()
        ls.append((i,word_count))       
    
    
    dict_ = dict(ls)
    
    print dict_
    

    output; {'and': 2, 'count': 1, 'used': 1, 'this': 1, 'is': 2, 'it': 1, 'to': 1, 'take': 1, 'words': 1, 'the': 1, 'textfile,': 1}

提交回复
热议问题