【问题标题】:Letter Count with Frequency, using Dictionaries字母计数频率,使用字典
【发布时间】:2020-03-21 09:34:45
【问题描述】:

我想知道是否有人可以帮助我。

如何让此代码仅将文本文件中字母的频率记录到字典中(不计算空格、行、数字等)?

另外,如何将每个字母除以总字母来报告文件中每个字母的百分比频率?

这是我目前拥有的:

def linguisticCalc():
    """
    Asks user to input a VALID filename. File must be a text file. IF valid, returns the frequency of ONLY letters in file.

    """
    filename = input("Please type your VALID filename")
    if os.path.exists(filename) == True:
        with open(filename, 'r') as f:
            f_content = f.read()
            freq = {}
            for i in f_content:
                if i in freq:
                    freq[i] += 1
                else:
                    freq[i] = 1
        print(str(freq))

    else:
        print("This filename is NOT valid. Use the getValidFilename function to test inputs.")

【问题讨论】:

  • 请展示你到目前为止所做的尝试。
  • 欢迎来到 SO。如果您希望我们完成您的任务,而您在解决过程中付出了零努力,那么您来错地方了。我们帮助更正代码。

标签: python dictionary count frequency letter


【解决方案1】:

查看collections.Counter()

您可以使用它来计算字符串中的每个字母:

Counter('Articles containing potentially dated statements from 2011')

它给出了这个输出,这对于计算字符串中的字符很有用:

计数器({'A': 1, 'r': 2, 't': 8, “我”:4, 'c': 2, 'l': 3, 'e': 5, 's': 3, ' ': 6, 'o': 3, 'n': 5, “一”:4, 'g': 1, 'p': 1, 'y': 1, 'd': 2, 'm': 2, 'f': 1, '2': 1, “0”:1, '1': 2})

【讨论】:

  • 我试过了,但它记录了空格、数字等。我需要只记录字母的东西。
【解决方案2】:

可以帮助您确定所讨论的字符是否是字母的东西,是这样的:

import string

# code here

if character in string.ascii_letters:
    # code here

【讨论】: