Python code example to finish calculating the word count of a text file

Source: Internet
Author: User
This article mainly describes the Python implementation of statistical text file Word Count method, involving Python for text file reading and string conversion, operation and other related operations skills, the need for friends can refer to the following

This paper describes how Python implements the word count of a statistical text file. Share to everyone for your reference, as follows:

Count the number of words in the text file, from the current directory of the File.txt to fetch files


#-*-CODING:GBK-*-import stringimport sysreload (SYS) def compareitems ((W1,C1), (W2,C2)):  if C1 > C2:    Return-  1  elif C1 = = C2:    return CMP (W1, W2)  else:    return 1def Main ():  fname = "file.txt"  try:    text = Open (fname, ' R '). Read ()    text = string.lower (text)  except:    print "\nfile.txt is not exist!!! Or there is a r/w error! "    Sys.exit () for  ch in '!" #$%& () *+,-./:;<=>?@[\\]^_ ' {|} ~ ':    Text = string.replace (text, ch, ')  words = string.split (text)  counts = {} for  w in words:    c OUNTS[W] = Counts.get (w,0) + 1  n = input ("\ n Enter the number of top words to Count:")  items = Counts.items ()  Items.Sort ( Compareitems)  max = len (items)  print "\ n Words total:" + str (words)  print "net number of words (removed):" + str (max)  print "\ n"  if n > Max:    n = max for  i in range (n):    print "%-10s%5d"% items[i]if name = = ' main ': 
  main ()

"Recommended"

1. Special Recommendation: "PHP Programmer Toolkit" V0.1 version download

2. Python Free video tutorial

3. Python Basics Introductory Tutorial

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.