當從string
模塊導入時,使用解析函數。在函數內部使用模塊時出現UnboundLocalError?
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'> !"#$%&'()*+,-./:;<=>[email protected][\]^_`{|}~
打印出細膩,無錯誤,並顯示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
返回錯誤?
你的最後一個例子假設'data'不需要重複或訂單。 – 2013-04-20 20:26:56
@Lattyware:它看起來像OP的代碼只是檢查字符串是否包含任何標點符號,所以我不認爲這需要任何順序。 – Blender 2013-04-20 20:28:08
這是一個很好的觀點,我沒有考慮它作爲測試的替代品。 – 2013-04-20 20:28:33