Python USES dictionaries to count examples of words or Chinese words

  • 2020-04-02 13:37:02
  • OfStack

There are text files in the following format


/ " / please / ! / " / " / please / ! / " / two / swordsmen / Their respective / reverse / tip / . / The right hand / hold / The sword handle / . 
/ The left hand / Take in / The right hand / The back of hand / . / Devoting to salute / . / two / people / The body / Has not yet been / standing / straight / . 
/ All of a sudden / between / Bai Guangshan / dynamic / . / Along with the / The zither / one / sound / . 
/ Sword two-phase / Hand in / . / two / people / each / Take a step back / . 
/ beside / The audience / people / all / is / " / yi / " / the / A cry, / Light shout / . / Tsing yi / swordsmen / even / split / three / The sword /

The word frequency statistics of this passage show that   Words, words   For example   please   2   , and put the results in a TXT file.

In this case, the word or word is used as the key of the dictionary. Loop to determine whether there is this key or not. If there is no new key, add 1 to the corresponding value of this key


#coding:utf-8
word_lst = []
word_dict = {}
with open(" Chinese .txt","r") as f1 ,open(" Number of words .txt",'w') as f2:
   for line in f1:
       word_lst.append(line.split('/'))
   for item in word_lst:
       for item2 in item:
           if item2.strip() not in " ,! . "" " :
               if   item2 not in word_dict:
                   word_dict[item2] = 1
               else :
                   word_dict[item2] += 1
   for key in word_dict:
       print key,word_dict[key]
       f2.write(key+' '+str(word_dict[key]))


Related articles: