Joe21
Joe21

Reputation: 45

Python - How many words are there in the .txt file in order by frequency and alphabetically?

Count how many words there are in the .txt file.

Then, print the words ordered by frequency and alphabetically.

def count_words():
    d = dict()
    word_file = open('words.txt')
    for line in word_file:
        word = line.strip();
        d = countwords(word,d)
    return d

I'm not sure if I am doing this correctly. Hoping someone can help me out.

When I run the program, I receive:

>>>
>>>

It's a paragraph of a speech.

Upvotes: 0

Views: 2431

Answers (2)

Tommy
Tommy

Reputation: 13672

I would use a dictionary like you are but differently:

def count_words():
d = dict()
word_file = open('words.txt')
for line in word_file:
    word = line.strip();
    if word not in d.keys():
        d[word] = 0
    d[word]+=1

Then you can sort the keys by their counts and print them:

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))

For the sorting blurb I used: Sort a Python dictionary by value

Also, your program doesnt have any print statements, just a return line, which is why you get nothing.

Upvotes: 2

dstromberg
dstromberg

Reputation: 7187

#!/usr/local/cpython-3.3/bin/python

import pprint
import collections

def words(filename):
    with open(filename, 'r') as file_:
        for line in file_:
            for word in line.split():
                yield word.lower()

counter = collections.Counter(words('/etc/services'))

sorted_by_frequency = sorted((value, key) for key, value in counter.items())
sorted_by_frequency.reverse()
print('Sorted by frequency')
pprint.pprint(sorted_by_frequency)
print('')

sorted_alphabetically = sorted((key, value) for key, value in counter.items())
print('Sorted alphabetically')
pprint.pprint(sorted_alphabetically)

Upvotes: 1

Related Questions