2011-04-14 69 views
3

我在寫一個程序,它打印出一個單詞的頻率如何,只要頻率在斐波那契數列(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') 
+1

你剛纔不是張貼了這個問題? http://stackoverflow.com/questions/5668969/python-using-the-fibonacci-sequence – 2011-04-14 22:48:28

+1

nope,問一個是多一點含糊,想出了一些東西,再次卡住 – Aaron 2011-04-14 22:58:27

+0

只要繼續調用a.next()從斐波那契發生器獲取下一個值。 – 2011-04-14 23:22:29

回答

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) 
+0

非常感謝你 – Aaron 2011-04-15 00:15:42

1

您在接下來調用時覆蓋生成器對象。

調用fib()返回一個生成器。要獲得下一個值,請使用返回值的next(a)。然後你將它分配給一個覆蓋你的發生器,所以你不能再使用它了。相反,執行如value = a.next()之類的操作,並在每次需要獲取fib序列中的下一個值時執行該操作。

順便說一句,它可能會更有意義,通過斐波那契數迭代,尋找那些在頻率上,而不是通過頻率迭代。否則,您將不得不重置您的斐波那契發生器每次。

您可以在列表中找到最大頻率,並在序列超過該值時停止斐波那契迭代。