【问题标题】:Python coding and testingPython编码和测试
【发布时间】:2021-09-06 18:43:48
【问题描述】:

您好,我正在尝试在单独的测试文件夹中测试我的代码,但每次我尝试对其执行 python3 测试时,它都会显示 NameError: name 'word_count' is not defined 即使我已导入文件夹如您所见,已定义此名称?任何人都可以帮忙吗? `

字数代码:

def word_count(str): 
counts = dict()
words = str.split()

for word in words:
    if word in counts:
        counts[word] += 1
    else:
        counts[word] = 1

return counts`

测试代码:

import wordcount 
print(word_count('the quick brown fox jumps over the lazy dog.'))
 

【问题讨论】:

  • 您能分享一下您的代码是如何共存的吗?是不是在同一个目录下?
  • 是的,它们都在同一个目录下,但我不知道为什么它没有看到导入

标签: python web-services terminal


【解决方案1】:

您必须从模块 wordcount 中导入函数 word_count(如果您的文件名为 wordcount.py),即:

from wordcount import word_count
print(word_count('the quick brown fox jumps over the lazy dog.'))

或者使用模块名称作为函数的前缀

import wordcount
    print(wordcount.word_count('the quick brown fox jumps over the lazy dog.'))

【讨论】:

  • 解决了,谢谢!我只是假设单独导入文件也会输入其所有括号。
【解决方案2】:

如果wordcount.py 和你的test_script.py 在同一个文件夹中,你能用wordcount.word_count(...) 试试吗?或者你可以使用这个导入语句:from wordcount import word_count

【讨论】:

  • 解决了,谢谢!我只是假设单独导入文件也会输入其所有括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2015-07-08
  • 1970-01-01
相关资源
最近更新 更多