reallilpunch
reallilpunch

Reputation: 93

How can i sort order of wordcount with Python?

I am using this code to count the same words in a text file.

filename = input("Enter name of input file: ")
file = open(filename, "r", encoding="utf8")
wordCounter = {}
with open(filename,'r',encoding="utf8") as fh:
  for line in fh:
    # Replacing punctuation characters. Making the string to lower.
    # The split will spit the line into a list.
    word_list = line.replace(',','').replace('\'','').replace('.','').replace("'",'').replace('"','').replace('"','').replace('#','').replace('!','').replace('^','').replace('$','').replace('+','').replace('%','').replace('&','').replace('/','').replace('{','').replace('}','').replace('[','').replace(']','').replace('(','').replace(')','').replace('=','').replace('*','').replace('?','').lower().split()
    for word in word_list:
      # Adding  the word into the wordCounter dictionary.
      if word not in wordCounter:
        wordCounter[word] = 1
      else:
        # if the word is already in the dictionary update its count.
        wordCounter[word] = wordCounter[word] + 1

print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)
# printing the words and its occurrence.
for  word,occurance  in wordCounter.items():
  print(word,occurance)

I need them to be in order in bigger number to smaller number as output. For example:

word 1: 25

word 2: 12

word 3: 5 . . .

I also need to get the input as just ".txt" file. If the user writes anything different the program must get an error as "Write a valid file name".

How can i sort output and make the error code at the same time ?

Upvotes: 2

Views: 182

Answers (2)

Wojciech
Wojciech

Reputation: 111

You can try:

if ( filename[-4:0] != '.txt'):
    print('Please input a valid file name')

And repeat input command...

Upvotes: 0

aminrd
aminrd

Reputation: 5000

For printing in order, you can sort them prior to printing by the occurrence like this:

for  word,occurance  in sorted(wordCounter.items(), key=lambda x: x[1], reverse=True):
  print(word,occurance) 

In order to check whether the file is valid in the way that you want, you can consider using:

import os

path1 = "path/to/file1.txt"
path2 = "path/to/file2.png"

if not path1.lower().endswith('.txt'):
    print("Write a valid file name")

if not os.path.exists(path1):
    print("File does not exists!")

Upvotes: 2

Related Questions