简体   繁体   中英

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 . It's not 99/88/77 always...just an example...I tried with:

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], [])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM