Python UnboundLocalError:局部变量';文档id';分配前参考
我正在尝试运行以下脚本,但继续收到一个错误,即我的变量“doc_id”在赋值之前被引用,我找不到解决方案。请参阅下面的代码。我不得不删掉一些代码,但如果有用的话,我很乐意发表评论 感谢您的帮助Python UnboundLocalError:局部变量';文档id';分配前参考,python,Python,我正在尝试运行以下脚本,但继续收到一个错误,即我的变量“doc_id”在赋值之前被引用,我找不到解决方案。请参阅下面的代码。我不得不删掉一些代码,但如果有用的话,我很乐意发表评论 感谢您的帮助 def writeBills(): bill_id_list= [] for item in js.values(): try: bill_id_list.append(item.get('bill_id')) except
def writeBills():
bill_id_list= []
for item in js.values():
try:
bill_id_list.append(item.get('bill_id'))
except KeyError:
pass
bills = getBills(bill_id_list)
num = 1
for bill in bills:
#iterate to the bill key
#get the doc_id to append to the API call
try:
bill_num = bill.get("bill").get("bill_number")
except AttributeError:
bill_num = "bill" + str(num)
try:
doc_id = bill.get("bill").get("texts")[0].get("doc_id")
except AttributeError:
pass
#append the doc_id to the API call and convert results to unicode string
searchId = urlopen('https://api.legiscan.com/?key=d43c289757d4acd3bdb73391fb60e97a&op=getBillText&id='+str(doc_id)).read().decode()
#create json object with API data
resultsId = json.loads(searchId)
#iterate to the document object
resultsId = resultsId.get('text').get('doc')
#decode the MIME 64 encoded text
decodedResults = base64.b64decode(resultsId)
#once decoded, the text is in an HTML string, use bs4 to parse it
bsObj2 = BeautifulSoup(decodedResults)
for p in bsObj2.find_all('p'):
if p.string:
p.string.replace_with(p.string.strip())
bsObj2.style.decompose()
#strip white space, encode in ascii and remove non-printing characters
htmlText = str(bsObj2.getText())
f = open("~/repos/LegiScanApiScrips/data/bills/" + str(bill_num) + "_" + str(doc_id) + ".txt", "wb")
print("Writing: "+ str(bill_num))
f.write(htmlText.encode("ascii", errors="ignore"))
f.close()
num += 1
writeBills()
试试看:
doc\u id=bill.get(“bill”).get(“text”)[0]。get(“doc\u id”)
除属性错误外:
通过
这里有一个
AttributeError
正在上升,您正在吞咽,因此doc\u id
没有被初始化。变量doc\u id
仅在没有AttributeError
但您正在以任何方式使用doc\u id
时才赋值
请尝试以下方法:
doc_id = bill.get("bill", {'text': [{}]}).get("texts")[0].get("doc_id")
尽量不要在应用程序流中包含异常处理。顺便说一句。这是您不应该只接受错误的几个原因之一(空的
除了块)…如果bill.get(“bill”).get(“text”)[0]。get(“doc_id”)
失败并出现AttributeError,则永远不会分配doc_id
,因此,在searchId=urlopen(“…”+str(doc_id)).read().decode()中使用它后,就不知道了。请尝试在函数范围中将doc_id设置为全局。doc_id
仅在Try
块中分配。如果该块中发生异常,则继续执行,并且没有为此变量指定任何值。您或者需要在块中指定一些备用值,除了
块(正如您刚才对bill_num
所做的那样),或者如果没有该变量,进一步执行将毫无意义,则中断循环。最后,这是一个设计问题。当您无法获得医生id时,您希望发生什么?也许这很好,你只要继续。也许它(以及潜在的索引和键错误)会变成提高价值错误(“比尔没有文档id”)
。为什么不涉及异常处理?简单地将通过
转换为继续是一个很好的方法,可以默默地忽略没有您想要的数据的账单。如果应用程序设计允许,它也是放置回退处理或日志记录的好地方。@tdelaney在流控制中使用异常不是一种反模式吗?