Python counts the number of words that appear

Source: Internet
Author: User

Python counts the number of words that appear

This article mainly introduces how to calculate the number of words in Python. This article provides the implementation code and usage methods. For more information, see

I recently read the python scripting language. It is an explanatory language and can be directly used without compilation. It is explained by the interpreter. The python language is powerful and concise. The following example uses python to calculate the number of words that appear.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Import sys

Import string

# Import collections

 

If len (sys. argv) = 1 or sys. argv [1] in {"-h", "-- help "}:

Print ("usage: uniqueword filename_1 filename_2... filename_n ")

Sys. exit ()

Else:

Words = {}

# Words = collections. defaultdict (int)

Strip = string. whitespace + string. punctuation + string. digits + "\"'"

For filename in sys. argv [1:]:

For line in open (filename ):

For word in line. split ():

Word = word. strip (strip)

If len (word)> = 2:

Words [word] = words. get (word, 0) + 1

# Words [word] + = 1

For word in sorted (words ):

Print ("'{0}' occurs {1} times". format (word, words [word])

Assume that the file name is uniqueword. py. Enter uniqueword. py filename_1 filename_2... filename_n in the command line to calculate the number of times the word appears.

The fourth and fifth rows determine whether there are input parameters. If the input parameter is null or-h or-help, the help information is output.

From Row 7 to row 14th is the core part. Open the Files specified in the parameters one by one, read each row, and extract words from the read rows using the string split method, when the word length is greater than 2, the word is added to the dictionary words. Where words. get (word, 0) means to retrieve the value whose key is equal to word. If the key is null, the value is set to the default value 0. Finally, the result is printed.

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.