簡體   English   中英

我如何讓python接受元素0和1(如果存在)而取元素0(如果元素1不存在)呢?

[英]How do I get python to take element 0 and 1 if they exist and take element 0 if element 1 does not exist?

嘗試運行代碼時出現“索引錯誤:列表索引超出范圍錯誤”。 本質上,我想確定在文檔中引用“項目1A”的所有時間,並保留該部分。 不幸的是,有些文檔有目錄(TOC),有些則沒有。 如果有一個目錄,那么我想要的元素就是元素1,當沒有目錄時,我想要元素0。我認為最簡單的就是只保留元素0和1,因為擁有一個元素不會有傷害從那里的TOC線。 不幸的是,我的代碼無法運行,因為在沒有TOC的情況下,我正在調用的元素(元素1)超出范圍。 知道如何讓元素0和1是否存在嗎? 這是我的代碼。 謝謝!

#Using the period will identify the header; references shouldn't have a period following
docm=re.split('Item 1A\.',doc, re.IGNORECASE)
#Element 0 of list should be the table of contents entry
docm=re.findall('Item 1A\..*?Item',doc, re.IGNORECASE)

#Identifies the next item after 1a (i.e. 1b or 2)
docs=re.sub(' |\.','',doc.split(docm[0])[1][:4]) 
#Finds all text between item 1a. and the next item, element 0 is table of contents, element 1 is what we want
docss=re.findall('item 1a\..*?item '+docs+'\.',doc,re.IGNORECASE)[0-1]

兩者都切成薄片,然后取出最后一個。

seq[0:2][-1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM