作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个程序,只要频率在斐波那契数列(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/
我是一名优秀的程序员,十分优秀!