簡體   English   中英

如何在文本文件中查找單詞?

[英]How to find words 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

如果其中一個是int ,則可以輕松地在一個條件下進行反向排序,並在另一個條件上轉發排序,通過否定鍵函數中的int

更換

freq_list.sort()

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

在更一般的情況下,由於Python的排序是穩定的,你可以按第二個鍵然后第一個鍵排序

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

缺點是你需要做兩種,所以它有點慢

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM