簡體   English   中英

我正在嘗試計算txt文件中的所有字母,然后按降序顯示

[英]I'm trying to count all letters in a txt file then display in descending order

正如標題所說:

到目前為止,這是我在我的代碼工作的地方,但我無法按順序顯示信息。 目前它只是隨機顯示信息。

def frequencies(filename):
    infile=open(filename, 'r')
    wordcount={}
    content = infile.read()
    infile.close()
    counter = {}
    invalid = "‘'`,.?!:;-_\n—' '"

    for word in content:
        word = content.lower()
        for letter in word:
            if letter not in invalid:
                if letter not in counter:
                    counter[letter] = content.count(letter)
                    print('{:8} appears {} times.'.format(letter, counter[letter]))

任何幫助將不勝感激。

字典是無序的數據結構。 此外,如果你想計算一組數據中的一些項目,你最好使用collections.Counter() ,這是為了這個目標更優化和pythonic。

然后你可以使用Counter.most_common(N)來打印Counter對象中的大多數N常用項目。

另外,關於文件的打開,您可以簡單地使用with語句自動關閉塊末尾的文件。 最好不要在函數內打印最終結果,你可以通過產生預期的線條然后在你想要的時候打印它們來使你的函數成為生成器。

from collections import Counter

def frequencies(filename, top_n):
    with open(filename) as infile:
        content = infile.read()
    invalid = "‘'`,.?!:;-_\n—' '"
    counter = Counter(filter(lambda x: not invalid.__contains__(x), content))
    for letter, count in counter.most_common(top_n):
        yield '{:8} appears {} times.'.format(letter, count)

然后使用for循環來迭代生成器函數:

for line in frequencies(filename, 100):
    print(line)

您不需要迭代'單詞',然后遍歷其中的字母。 迭代字符串(如content )時,您將擁有單個字符(長度為1個字符串)。 然后,您需要在計數循環之后等待,直到顯示輸出。 計數后,您可以手動排序:

for letter, count in sorted(counter.items(), key=lambda x: x[1], reverse=True):
    # do stuff

但是,最好使用collections.Counter

from collections import Counter

content = filter(lambda x: x not in invalid, content)
c = Counter(content)
for letter, count in c.most_common():  # descending order of counts
    print('{:8} appears {} times.'.format(letter, number))
# for letter, number in c.most_common(n):  # limit to n most
#     print('{:8} appears {} times.'.format(letter, count))

以降序顯示需要在搜索循環之外,否則它們將在遇到時顯示。

在按降序排序是很容易使用內置的sorted (你需要設置reverse -argument!)

然而,python 包含電池,並且已經有一個Counter 所以它可以簡單如下:

from collections import Counter
from operator import itemgetter

def frequencies(filename):
    # Sets are especially optimized for fast lookups so this will be
    # a perfect fit for the invalid characters.
    invalid = set("‘'`,.?!:;-_\n—' '")

    # Using open in a with block makes sure the file is closed afterwards.
    with open(filename, 'r') as infile:  
        # The "char for char ...." is a conditional generator expression
        # that feeds all characters to the counter that are not invalid.
        counter = Counter(char for char in infile.read().lower() if char not in invalid)

    # If you want to display the values:
    for char, charcount in sorted(counter.items(), key=itemgetter(1), reverse=True):
        print(char, charcount)

Counter已經有一個most_common方法,但你想顯示所有字符和計數,所以它不適合這種情況。 但是,如果您只想知道x最常見的計數,那么它將是合適的。

您可以使用已sorted方法在打印時對字典進行sorted

lettercount = {}
invalid = "‘'`,.?!:;-_\n—' '"
infile = open('text.file')
for c in infile.read().lower():
    if c not in invalid:
        lettercount[c] = lettercount.setdefault(c,0) + 1
for letter in sorted(lettercount):
    print("{} appears {} times".format(letter,lettercount[letter]))

Rmq:當我們第一次遇到一封信時,我使用了setdefault change方法將默認值設置為0

暫無
暫無

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

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