【问题标题】:Why isn't my function recognized in the REPL为什么我的函数在 REPL 中没有被识别
【发布时间】:2020-11-03 07:41:06
【问题描述】:

由于某种原因,当我在 REPL 中运行我的程序时,我的模块无法识别。我输入 from import words (fetch_words, print_words) 并收到错误 fetch_words is not defined。当我输入 import words

时也会发生这种情况
from urllib.request import urlopen

def fetch_words():
    story = urlopen('https://sixty-north.com/c/t.txt')
    story_words = []
    for line in story:
        line_words = line.decode('utf-8').split()
        for word in line_words:
            story_words.append(word)
    story.close()
    return story_words



def print_words(story_words):
    for word in story_words:
        print(word)


def main():
    words = fetch_words
    print_words(words)


if __name__ == '__main__':
    main() 

【问题讨论】:

  • 你能把另一个文件的内容也放上去吗?还有各自的文件名?
  • 你能提供整个追溯吗?
  • 这是我唯一的文件。它的标签是 practice.py 我使用用户/桌面/文件访问提示。然后我输入 python 并导入导致我出现此错误的单词。 @AstikGabani Traceback(最近一次调用最后一次):文件“”,第 1 行,在 ModuleNotFoundError: No module named 'words'
  • @c_reyes 您输入的具体内容是什么?
  • 从 urllib.request 导入 urlopen

标签: python python-3.x read-eval-print-loop


【解决方案1】:

导入函数时语法不正确。

由于您已将文件命名为practice.py,因此导入其中定义的函数的正确语法为:

from practice import fetch_words

或者如果您需要导入多个函数:

from practice import fetch_words, print_words

记住,要导入的模块的名称应该与文件的名称相同,没有.py 扩展名。在这种情况下,模块是practice,而不是words

【讨论】:

  • 语法其实没问题,就是名字不对。
  • @wjandrea 乍一看他的语法对我来说似乎是错误的。也许他那里有一个错字。
  • @bikalpa 哦,你说得对,from import words ... 无效。但这会导致不同的错误,所以我认为这是写问题时的拼写错误。
  • @c_reyes 如果它解决了您的问题,请接受答案,以便其他面临相同问题的程序员可以解决他们的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-23
  • 2022-07-11
相关资源
最近更新 更多