How to calculate the frequency of occurrence of words in a text string in python

Source: Internet
Author: User

How to calculate the frequency of occurrence of words in a text string in python

This example describes how to calculate the frequency of occurrence of words in a python text string. Share it with you for your reference. The specific implementation method is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

# Word frequency in a text

# Tested with Python24 vegaseat 25aug2005

# Chinese wisdom...

Str1 = "" Man who run in front of car, get tired.

Man who run behind car, get exhausted ."""

Print "Original string :"

Print str1

Print

# Create a list of words separated at whitespaces

WordList1 = str1.split (None)

# Strip any punctuation marks and build modified word list

# Start with an empty list

WordList2 = []

For word1 in wordList1:

# Last character of each word

Lastchar = word1 [-1:]

# Use a list of punctuation marks

If lastchar in [",",".","! ","? ","; "]:

Word2 = word1.rstrip (lastchar)

Else:

Word2 = word1

# Build a wordList of lower case modified words

WordList2.append (word2.lower ())

Print "Word list created from modified string :"

Print wordList2

Print

# Create a wordfrequency dictionary

# Start with an empty dictionary

FreqD2 = {}

For word2 in wordList2:

FreqD2 [word2] = freqD2.get (word2, 0) + 1

# Create a list of keys and sort the list

# All words are lower case already

KeyList = freqD2.keys ()

KeyList. sort ()

Print "Frequency of each word in the word list (sorted ):"

For key2 in keyList:

Print "%-10 s % d" % (key2, freqD2 [key2])

I hope this article will help you with Python programming.

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.