【问题标题】:Why is my for loop not returning anything?为什么我的 for 循环不返回任何内容?
【发布时间】:2019-12-02 17:57:07
【问题描述】:

我刚开始自学编程,我已经使用 Python 3.0(Anaconda 发行版)在 Jupyter 笔记本中编写了一个小程序,该程序应该接收一个单词并返回 JSON 文件中的所有单词与您输入的单词押韵。我发现当我运行它时,我什么也得不到。我绞尽脑汁想我在这里做错了什么——我敢肯定这是我错过的一些愚蠢的事情。

import json

english_words = open('C:/Users/thoma/Documents/Programs/Python Programs/Rhyme Machine/words_dictionary.json', 'r')
rhymee = input('give me a word and ill return you all the words that rhyme with it. ')
rhymers = []

for word in english_words:
    if len(word) > 3 and word[-3:] == rhymee[-3:]:
        rhymers.append(word)
    else:
        pass
print(rhymers)

【问题讨论】:

  • 这取决于 JSON 文件的格式。请给我们举个例子。

标签: python json loops for-loop


【解决方案1】:

您在该代码中没有read() 函数,因此英文单词仅包含文件对象而不包含数据。尝试先读取文件然后执行for 循环。玩转并尝试打印英文单词variable。

【讨论】:

  • 在 Python 中,您可以以这种方式使用for 循环遍历文件的内容,而无需使用read()。问题是word 将是文件中的一行,而不是一个单词,因为文件是 JSON 格式,这里没有代码可以将其解析为 JSON。
猜你喜欢
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 2016-11-26
  • 1970-01-01
  • 2020-09-25
  • 2012-04-02
  • 2018-01-24
  • 1970-01-01
相关资源
最近更新 更多