python - 使用斐波那契数列打印出单词

标签 python

我正在编写一个程序,只要频率在斐波那契数列(1、2、3、5、8 等)中,它就会打印出单词的频率。我已经想出如何打印出现一次的所有单词,但是我无法弄清楚如何迭代以打印出频率更高的单词。

import string
import itertools

def fib():
    a,b = 0, 1
    while 1:
        yield b
        a, b = b, a + b

while True:
    filename = raw_input('Enter a file name: ')
    if filename == 'exit':
        break
    try:
        file = open(filename, 'r') 
        text = file.read() 
        file.close() 
    except:
        print('file does not exist')
    else:

        for word in string.punctuation:
            text=text.replace(word, "")
        word_list = text.lower().split(None)
        word_freq = {}

        for word in word_list:
            if len(word) > 1:
                word_freq[word] = word_freq.get(word, 0) + 1

        frequencies = sorted(word_freq.items(), key=lambda item: item[1])
        a = fib()
        order = sorted(word_freq.values())
        n = 1
        a = next(a)
        for words in frequencies:
            try:
                if a == words.index(n):
                    print(words)
            except:
                print('nope')  # HELP: how would I iterate here??


print('Bye')

最佳答案

尝试将 while 循环的结尾更改为以下内容:

    f = next(a)
    for words in frequencies:
        # we need a new value from fib, since we have passed the current one
        while words[1] > f:
            f = next(a)
        # if the frequency of this word matches the fib value, print it
        if words[1] == f:
            print(words)

关于python - 使用斐波那契数列打印出单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670573/

相关文章:

python - 在 python 中设置 rdf 三重存储的好解决方案?

python - python对象的自定义过滤函数

Python:由于 OSError 无法安装软件包:[Errno 2] 没有这样的文件或目录

python - 以 'rt' 和 'wt' 模式打开文件

python - 如何使用groupby中的两个组计算百分比?

python - vim:.vimrc 无法正确加载 python 文件

python 子进程在正在运行的子进程中插入命令

python - Mac OS - 安装 python-spidermonkey 失败,因为找不到 nspr

python - 与 pandas 一起使用 re.match 时出现“预期的字符串或缓冲区”

python - 如何使用正则表达式在字符串中查找美国邮政编码?