从string
模块导入时,与解析函数一起使用。
from string import punctuation
def parsing_func(data):
if not any(i==v for i in data for v in punctuation.replace('_', '')):
print data
在上面的这个函数中使用string
' punctuation
,一切正常。
然后我想对照几个较少的标点符号检查数据。所以我改成parsing_func
这样:
def parsing_func(data):
punctuation = punctuation.replace('_', '')
punctuation = punctuation.replace('()', '')
if not any(i==v for i in data for v in punctuation):
print data
但这会返回:
Traceback (most recent call last):
File "parser.py", line 58, in <module>
parsing_func(data)
File "ex.py", line 8, in parsing_func
punctuation = punctuation.replace('_', '')
UnboundLocalError: local variable 'punctuation' referenced before assignment
所以,我做了一个测试功能来检查punctuation
:
def test_func1():
print type(punctuation), punctuation
>>> <type 'str'> !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
打印出来很好,没有错误,并显示type str
. 最后,我尝试将print
一个接一个的字符串操作放在一起。
def test_func2():
print type(punctuation), punctuation
punctuation = punctuation.replace('_', '')
但现在该print
语句返回错误:
Traceback (most recent call last):
File "parser.py", line 9, in <module>
test_func2()
File "parser.py", line 5, in test_func2
print type(punctuation), punctuation
UnboundLocalError: local variable 'punctuation' referenced before assignment
这是一个namespace
错误吗?为什么test_func2
在打印而不是字符串操作时会返回错误?