gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:53:24 25 4
gpt4 key购买 nike

我正在编写一个程序,只要频率在斐波那契数列(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com