[英]How to extract specific digits after underscore from filename in python
I have a number of file names like: 我有许多文件名,如:
/home/abc/xyz/12345_993456_pqr
/home/abc/xyz/12345_883456_pqr
/home/abc/xyz/12345_773456_pqr
I need to extract the first two digits right after the first underscore ie 99
or 88
or 77
. 我需要在第一个下划线后面提取前两个数字,即
99
或88
或77
。 It's not 99/88/77
always...just an example...I tried with: 它不是
99/88/77
总是......只是一个例子......我尝试过:
re.search()
and 和
isdigit()
but its not working. 但它不起作用。 Could anybody please help out?
有人可以帮忙吗?
Step by step: 一步步:
>>> import os
>>> os.path.basename('/home/abc/xyz/12345_993456_pqr')
'12345_993456_pqr'
>>> os.path.basename('/home/abc/xyz/12345_993456_pqr').split('_')
['12345', '993456', 'pqr']
>>> os.path.basename('/home/abc/xyz/12345_993456_pqr').split('_')[1]
'993456'
>>> os.path.basename('/home/abc/xyz/12345_993456_pqr').split('_')[1][:2]
'99'
ok this is quite tricky but try this: 好吧这很棘手,但试试这个:
import os, re
reg_exp = re.compile('_\d\d')
digits = [j[1:] for j in sum([reg_exp.findall(os.path.basename(i))[:1]
for i in filenames], [])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.