Example of using a dictionary to count the number of words or Chinese Characters in python

Source: Internet
Author: User

Text files in the following format
Copy codeThe Code is as follows:
/"/Please /! /"/"/Please /! /"/Two/swordsmen/respective/reverse//,/right hand/Grip/hilt /,
/Left hand/Attach/right hand/,/bow /. /Two/person/body/not yet/station/straight /,
/Suddenly/room/white flashing/animation/,/followed by/else/1/sound /,
/Pair of swords/intersection/,/Two/person/each/step back /.
/Side/audience/people/both/Yes/"/audience/"/A/call /. /Tsing Yi/swordsman/connection/split/3/sword/

Perform Word Frequency Statistics in this section. The result is in the form of word-number. For example, please 2 and put the result in a txt file.

In this case, words or words are used as the dictionary key to cyclically judge whether the key exists and no new one is added. If yes, add 1 to the value corresponding to the key.

Copy codeThe Code is as follows:
# Coding: UTF-8
Word_lst = []
Word_dict = {}

With open ("Chinese .txt", "r") as f1, open ("Word Count .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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.