我已经编写了一些Python代码来解析目录中的文件名和元数据。文件没有一致的命名约定,但每个文件名都包含一个我需要提取的六位数。我能在命名约定中找到的唯一一致性是下划线的使用
我已经能够使用下面的代码相当成功地提取这些数字,但是有一些文件不起作用,我正在尝试理解我需要调整什么来捕获最后几个
df = new_df_meta['file']
len(df)
r = re.compile('[0-9][0-9][0-9][0-9][0-9][0-9]')
n = re.compile(r'\b\d{6,6}\b')
newlist = list(filter(r.findall, df))
len(newlist)
newlistres0 = [(sub.split('_')[2]) for sub in newlist]
newlistres1 = [(sub.split('_')[1]) for sub in newlist]
newlistres2 = [(sub.split('_')[0]) for sub in newlist]
newlistres = newlistres0 + newlistres1 + newlistres2
下面是我无法成功提取六位数(565244)的剩余文件名之一的示例:
09.10_ad epx_SI544015_565244_en12_20_2020_2019财年_44781_08251594.pdf
我尝试添加下面的代码行,但收到一条错误消息,即“列表索引超出范围”
newlistres3 = [(sub.split('_')[3]) for sub in newlist]
如有任何建议,将不胜感激
我收到的错误是:
IndexError
Traceback (most recent call last)
<ipython-input-146-20c18449951e> in <module>
13 newlistres1 = [(sub.split('_')[1]) for sub in newlist]
14 newlistres2 = [(sub.split('_')[0]) for sub in newlist]
---> 15 newlistres3 = [(sub.split('_')[3]) for sub in newlist]
16 # newlistres4 = [(sub.split('_')[4]) for sub in newlist]
17
<ipython-input-146-20c18449951e> in <listcomp>(.0)
13 newlistres1 = [(sub.split('_')[1]) for sub in newlist]
14 newlistres2 = [(sub.split('_')[0]) for sub in newlist]
---> 15 newlistres3 = [(sub.split('_')[3]) for sub in newlist]
16 # newlistres4 = [(sub.split('_')[4]) for sub in newlist]
17
IndexError: list index out of range
问题是
\b
永远不会与_
匹配您必须搜索下划线,后跟6位数字,后跟下划线,然后仅提取匹配的数字
(?:)
表示非捕获组_|^
匹配字符串前面的下划线或开头_|$
匹配字符串末尾的下划线或现在您只需遍历文件列表;没有必要对
filter
之类的东西着迷相关问题 更多 >
编程相关推荐