简体   繁体   中英

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.

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.

#!/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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM