Python implements the method of counting the number of words in text files

  • 2020-05-30 20:34:15
  • OfStack

In this paper, the example of Python to achieve the statistical text file word count method. I will share it with you for your reference as follows:

To count the number of words in a text file, fetch the file from file.txt in the current directory


# -*- coding: GBK -*-
import string
import sys
reload(sys)
def compareItems((w1,c1), (w2,c2)):
  if c1 > c2:
    return - 1
  elif c1 == c2:
    return cmp(w1, w2)
  else:
    return 1
def 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:
    counts[w] = counts.get(w,0) + 1
  n = input("\n Enter the statistics top Number of words :")
  items = counts.items()
  items.sort(compareItems)
  max = len(items)
  print "\n A total of words :" + str(len(words))
  print " Net number of words ( Have to heavy ):" + str(max)
  print "\n"
  if n > max:
    n = max
  for i in range(n):
    print "%-10s%5d" % items[i]
if __name__ == '__main__':
  main()

PS: here are two more convenient statistical tools for your reference:

Online word count tool:
http://tools.ofstack.com/code/zishutongji

Online character statistics and editing tools:
http://tools.ofstack.com/code/char_tongji

More about Python related content interested readers to view this site project: "Python file and directory skills summary", "Python skills summary text file", "Python data structure and algorithm tutorial", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article has been helpful to you in Python programming.


Related articles: