如果元素存在,如何让python获取元素0和1,如果元素1不存在,如何获取元素0?

时间:2018-02-26 18:36:49

标签: python python-3.x

我得到"索引错误:列表索引超出范围错误"当我尝试运行我的代码时。基本上,我想要识别所有的时间"项目1A和#34;在我的文档中引用并保留该部分。不幸的是,有些文件有一个目录(TOC),有些没有。如果有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]

0 个答案:

没有答案