使用正则表达式从文件名中提取6位数字

2024-10-02 02:29:59 发布

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

我已经编写了一些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

Tags: 文件代码inredfforlen文件名
1条回答
网友
1楼 · 发布于 2024-10-02 02:29:59

问题是\b永远不会与_匹配

您必须搜索下划线,后跟6位数字,后跟下划线,然后仅提取匹配的数字

searcher = re.compile(r"(?:_|^)(\d{6})(?:_|$)")
  • (?:)表示非捕获组
  • _|^匹配字符串前面的下划线开头
  • _|$匹配字符串末尾的下划线

现在您只需遍历文件列表;没有必要对filter之类的东西着迷

newlistres = []
for filename in df:
    m = searcher.search(filename)
    if m is None:
        continue
    newlistres.append(m.group(1))

相关问题 更多 >

    热门问题