我正在编写一个程序,它打印出一个单词的频率,只要频率在斐波那契序列(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')
答案 0 :(得分:1)
下次调用时,您将覆盖生成器对象。
调用fib()
会返回一个生成器。要获取下一个值,请使用返回值的next(a)
。然后将其分配给a,覆盖您的生成器,这样您就不能再使用它了。相反,做一些类似value = a.next()
的操作,并在每次需要获取fib序列中的下一个值时执行。
顺便说一下,迭代斐波那契数并在频率中寻找那些,而不是迭代频率可能更有意义。否则,您每次都必须重置斐波纳契生成器。
您可以在列表中找到最大频率,并在序列超过该值后停止斐波纳契迭代。
答案 1 :(得分:1)
尝试将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)