I am writing a program where it prints out how the frequency of a word as long as the frequency is in the fibonacci sequence (1,2,3,5,8,etc). I have figured out how to print all the words that appear once, however I am having trouble figuring out how to iterate so it prints out the words that have a higher freqeuncy.
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')
Try changing the end of your while
loop to the following:
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)
You're overwriting the generator object when you call next.
Calling fib()
returns a generator. To get the next value, you use next(a)
which returns the value. Then you assign it to a, which overwrite your generator, so you can't use it anymore. Instead, do something like value = a.next()
, and execute that each time you need to get the next value in the fib sequence.
By the way, it would probably make more sense to iterate through fibonacci numbers and look for those in the frequencies, rather than iterating through the frequencies. Otherwise, you'll have to reset your fibonacci generator every time.
You can find the max frequency in the list, and stop your fibonacci iteration once the sequence has exceeded that value.
精彩评论