全局名称're'未定义

时间:2021-12-31 16:48:26

I am new to python and working on a map reduce problem with mincemeat. I am getting the following error while running the mincemeat script.

我是python的新手,在地图上工作减少了百果馅的问题。运行mincemeat脚本时出现以下错误。

$python mincemeat.py -p changeme localhost
error: uncaptured python exception, closing channel <__main__.Client connected at 0x923fdcc> 
(<type 'exceptions.NameError'>:global name 're' is not defined
 [/usr/lib/python2.7/asyncore.py|read|79]
 [/usr/lib/python2.7/asyncore.py|handle_read_event|438] 
 [/usr/lib/python2.7/asynchat.py|handle_read|140]
 [mincemeat.py|found_terminator|96]
 [mincemeat.py|process_command|194]
 [mincemeat.py|call_mapfn|170]
 [raw1.py|mapfn|43])

My code rests in raw1.py script which is given in the above stacktrace as [raw1.py|mapfn|43].

我的代码位于raw1.py脚本中,该脚本在上面的stacktrace中给出为[raw1.py | mapfn | 43]。

import re
import mincemeat

# ...

allStopWords = {'about':1, 'above':1, 'after':1, 'again':1}

def mapfn(fname, fcont):
    # ...
    for item in tList[1].split():
        word = re.sub(r'[^\w]', ' ', item).lower().strip()        # ERROR
        if (word not in allStopWords) and (len(word) > 1):
            # ....

I have already imported re in raw1.py. The error doesn't appear if I import re in mincemeat.py.

我已经在raw1.py中导入了re。如果我在mincemeat.py中导入re,则不会出现该错误。

3 个解决方案

#1


12  

You need to have the import statement in mapfn itself. mapfn gets executed in a different python process, so it doesn't have access to the original context (including imports) in which it was declared.

您需要在mapfn中拥有import语句。 mapfn在不同的python进程中执行,因此它无权访问声明它的原始上下文(包括导入)。

#2


4  

"Global" variables in python are actually scoped to the module/file they're bound in; you do need to import them in every file that uses them.

python中的“全局”变量实际上是作用于它们所绑定的模块/文件;你需要在每个使用它们的文件中导入它们。

A module name is just a variable like anything else.

模块名称只是一个变量,就像其他任何东西一样。

#3


0  

It sounds like you've already answered this question. If you use re in mincemeat.py, you'll need to import re there as well.

听起来你已经回答了这个问题。如果你在mincemeat.py中使用re,你也需要在那里导入re。

#1


12  

You need to have the import statement in mapfn itself. mapfn gets executed in a different python process, so it doesn't have access to the original context (including imports) in which it was declared.

您需要在mapfn中拥有import语句。 mapfn在不同的python进程中执行,因此它无权访问声明它的原始上下文(包括导入)。

#2


4  

"Global" variables in python are actually scoped to the module/file they're bound in; you do need to import them in every file that uses them.

python中的“全局”变量实际上是作用于它们所绑定的模块/文件;你需要在每个使用它们的文件中导入它们。

A module name is just a variable like anything else.

模块名称只是一个变量,就像其他任何东西一样。

#3


0  

It sounds like you've already answered this question. If you use re in mincemeat.py, you'll need to import re there as well.

听起来你已经回答了这个问题。如果你在mincemeat.py中使用re,你也需要在那里导入re。