What are the methods of Python word frequency statistics
This article will explain in detail what are the methods of Python word frequency statistics. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Count the number of words in the file:
Count the words in the document and the number of times they appear
Save it with two lists, and then connect the output with the zip () function * *
Idea to set up and start practice method 1: # Import file with open ("passage.txt",'r') as file: dates = file.readlines () # handle words = [] for i in dates: words + = i.replace ("\ n", "). Split (") # replace the newline words + with empty characters in order not to be overwritten + there will be only the last piece of data # print ("\ n"). "). Split (")) setWords = list (set (words)) # set automatic deduplication num = [] # count the number of times a word appears for k in setWords: count = 0 for j in words: if k = = j: count = count + 1 num.append (count) print (num) print (setWords) # output for x, y in zip (setWords) Num): # combine two lists with zip print (x + ":" + str (y)),
Effect picture:
Method 2:
This method is used for dictionaries, which is a little simpler than the previous one.
# Import with open ("passage.txt",'r') as file: dates = file.readlines () # handle words = [] for i in dates: words + = i.replace ("\ n", "). Split (") # print (i.replace ("\ n") ") .split (")) # setWords=list (set (words)) # can not use this print (words) print ("-" * 40) # print (setWords) diccount = dict () for i in words: if (i not in diccount): diccount [I] = 1 # the first dictionary assignment is equivalent to iTunes 1 I is the word # print (diccount) else in words: diccount [I] = diccount [I] + 1 # and all the ergodic assignments are in it. Let's count print (diccount).
Effect picture:
Statistical documentation
This is the end of this article on "what are the methods of Python word frequency statistics". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.