简体   繁体   English

如何在文本文件中查找单词?

[英]How to find words in a text file?

I am writing a Python program to which I need to count how many of each word there are in a text file. 我正在编写一个Python程序,我需要计算一个文本文件中每个单词的数量。

def count_words(word,d):
    for l in word:
        if l in d:
            d[l] += 1
        else:
            d[l] = 1
        return d

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

You can easily get away with reverse sorting on one condition and forward sorting on another if one of them is an int by negating the int in the key func 如果其中一个是int ,则可以轻松地在一个条件下进行反向排序,并在另一个条件上转发排序,通过否定键函数中的int

replace 更换

freq_list.sort()

with

freq_list.sort(key=lambda x:(-x[1], x[0]))

In the more general case, since Python's sort is stable you can sort by the second key and then the first 在更一般的情况下,由于Python的排序是稳定的,你可以按第二个键然后第一个键排序

freq_list.sort(key=lambda x:x[0])
freq_list.sort(key=lambda x:x[1], reverse=True)

The disadvantage is that you need to do two sorts, so it's a little slower 缺点是你需要做两种,所以它有点慢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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