【发布时间】:2015-08-24 09:57:56
【问题描述】:
当我通过导入使用函数时,为什么会失败?它说“重新”未定义。我还尝试使用def x(): return 5+5 之类的基本函数,但也引发了错误。
作为导入使用时函数失败
import re
from sys import argv
from Galvanize import q1
f = open('git_script.txt','r')
q1.text_content_analyzer(f)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-82-cdff728a66aa> in <module>()
1 f = open('git_script.txt','r')
----> 2 q1.text_content_analyzer(f)
/Users/Rafeh/Dropbox/github/Galvanize/q1.py in text_content_analyzer(f)
6 wordsCount = {}
7
----> 8 for line in f:
9 nbOfSentences += len(re.split(r'[.!?]+', line.strip()))-1
10 lineWords = line.split()
NameError: name 're' is not defined
函数正常运行成功
def text_content_analyzer(f):
import re
words = []
nbOfSentences = 0
punctuation = []
wordsCount = {}
for line in f:
nbOfSentences += len(re.split(r'[.!?]+', line.strip()))-1
lineWords = line.split()
words = words + lineWords
for word in lineWords:
if word in wordsCount:
wordsCount[word] += 1
else:
wordsCount[word] = 1
print("Total word count: %1.0f" %len(words))
print(wordsCount)
print("Unique words: " , len(wordsCount.keys()))
print(nbOfSentences)
return len(words), wordsCount, len(wordsCount.keys()), nbOfSentences
现在我只是在测试和学习如何使用我自己的函数,但我目前在这里遇到了问题。
【问题讨论】:
-
我很确定
re需要成为一个类.. 然后你会这样做:`from re import x' 可能为什么它不起作用 -
哎呀。忘了补充说我的函数里面有
import re。接得好。 (我只是忘了把那行放在堆栈溢出中)。您的答案不正确,因为re是我用于字符串处理的模块。这就是为什么我的函数可以正常运行(没有被导入)。我只是不明白为什么它现在不运行(导入后)。 -
是不是就像您之前在脚本中错过了
import re,然后将其导入ipython,但由于该错误而失败,然后您通过添加import re修复它然后再次导入到同一个 ipython 会话后,它仍然不起作用? -
@Rafeh 你向我们展示的错误是说你没有导入
re,现在你告诉我们你只是碰巧忘记了包含@ 987654330@进入stackoverflow代码?我不想称你为骗子,但也许你的问题是你没有导入re, -
在复制和粘贴到这里之前,我恢复到了不正确的代码版本。我之前发现了
import re问题,并且它不在我的函数中,所以我更新了它。但是我发现了问题。在对 q1.py 文件进行更改后,我不得不关闭当前的 Ipython 笔记本并重新打开它。更改为import re。 @MarkusMeskanen 您的评论让我考虑重新启动浏览器并在放弃之前再次尝试,所以谢谢哈哈。你的评论让我重新思考。我已经在那里敲了一段时间的头。很抱歉这么简单的解决方案!
标签: python python-3.x ipython-notebook python-import