python - 我正在尝试使用 python 制作频率分析程序,但遇到问题

标签 python frequency-analysis

目前我已经做到了,以便程序可以计算给定消息中的字母频率,但在“descending_order”函数中,它一直说 LetterCountTuple 未定义,因此对其进行排序,它不会打印出“new_letter_count”,它不会反转“new_letter_count”,也不会打印出降序我以为我在函数和 main 中定义了它,我是否遗漏了一些东西?任何人都可以帮忙吗!到目前为止我的代码是这样的:

def main():
    message = input("please enter message")
    letterCount = getLetterCount(message)

    LetterCountTuple,new_letter_count,descending = descending_order(letterCount)


def getLetterCount(message):
    letterCount = {'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0}
    for letter in message.upper():
        if letter in letterCount:
            letterCount[letter] += 1

    print(letterCount)
    return letterCount


def descending_order(letterCount):
    letterCountTuple = letterCount.items()
    new_letter_Count = LetterCountTuple.sort
    print(new_letter_Count)
    descending = reversed(new_letter_Count)
    print(descending)
    return new_letter_Count, descending

main()

最佳答案

您有多个问题,descending_order 返回两个值,因此您将无法解压三个值,您也永远不会调用排序 LetterCountTuple.sort,您缺少括号 LetterCountTuple.sort ()

LetterCountTuple 是在 main 中定义的,而不是在 descending_order 中定义的,它应该是 letterCountTuple。

您还需要 new_letter_Count = Sorted(letterCountTuple),目前您正在将 new_letter_Count 分配给 None(如果您实际调用它),即.sort 的返回值,因为它是就地操作:

def descending_order(letterCount):
    letterCountTuple = letterCount.items()
    # create actual list of sorted letterCountTuple
    new_letter_Count = sorted(letterCountTuple)
    # reverse the list
    descending = new_letter_Count[::-1]
    # return three elements to unpack in main
    # LetterCountTuple,new_letter_count,descending = descending_order(letterCount)
    return letterCountTuple ,new_letter_Count, descending

我使用 new_letter_Count[::-1] 来反转列表,因为反转将返回一个 listreverseiterator 对象,如果需要,您必须在其上调用 list查看列表,因此在这种情况下有点多余。

顺便说一句,您应该使用下划线和小写字母 letter_count_tuplenew_letter_count 等来命名变量。

关于python - 我正在尝试使用 python 制作频率分析程序,但遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697217/

相关文章:

python - 在 Flask-SQLAlchemy 中添加 __init__() 方法

python - 有没有办法在进行正则表达式匹配时使用出现次数的范围?

mysql - 检查帖子频率是否为垃圾邮件的好算法

ios - 执行 FFT 以查找和弦音频样本的基频

c++ - FFT和IFFT的长度

python - 在不循环的情况下堆叠和整形 DataFrame (pandas) 的切片

python - 如何将值传递给 Pytest fixture

python - Google App Engine 远程 API + OAuth

algorithm - 在大量文本中查找最常见短语的高效算法

math - 将实部和虚部 FFT 输出转换为频率和幅度