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
def compareItems((w1,c1), (w2,c2)):
  if c1 > c2:
    return - 1
  elif c1 == c2:
    return cmp(w1, w2)
    return 1
def main():
  fname = "file.txt"
    text = open(fname,'r').read()
    text = string.lower(text)
    print "\nfile.txt is not exist!!! or There is a R/W error! "
  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()
  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__':

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

Online word count tool:

Online character statistics and editing tools:

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: