我在寫一個程序,它打印出一個單詞的頻率如何,只要頻率在斐波那契數列(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')
你剛纔不是張貼了這個問題? http://stackoverflow.com/questions/5668969/python-using-the-fibonacci-sequence – 2011-04-14 22:48:28
nope,問一個是多一點含糊,想出了一些東西,再次卡住 – Aaron 2011-04-14 22:58:27
只要繼續調用a.next()從斐波那契發生器獲取下一個值。 – 2011-04-14 23:22:29