UnboundLocalError:分配前引用的局部变量“doc\u id”

2024-09-30 16:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行以下脚本,但继续收到一个错误,即我的变量“doc_id”在赋值之前被引用,我找不到解决方案。请参阅下面的代码。我不得不删掉一些代码,但如果有用的话,我很乐意发表评论

感谢您的帮助

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()


Tags: thetoinidforgetstringdoc
2条回答
try:
    doc_id = bill.get("bill").get("texts")[0].get("doc_id")
except AttributeError:
    pass

这里有一个AttributeError正在被提升,你正在吞咽,所以doc_id没有被初始化

变量doc_id仅在没有AttributeError但您正在以任何方式使用doc_id时才赋值

请尝试以下方法:

doc_id = bill.get("bill", {'text': [{}]}).get("texts")[0].get("doc_id")

顺便说一句,不要在应用程序流中涉及异常处理

相关问题 更多 >