我在PYthon 2.7中有以下字符串列表:
list_a = ['temp_52_head sensor,
uploaded by TS','crack in the left quadrant, uploaded by AB, Left in 2hr
sunlight','FSL_pressure, uploaded by RS, no reported vacuum','art
9943_mercury, Uploaded by DY, accelerated, hurst potential too
low','uploaded by KKP, Space 55','avogadro reading level,
uploaded by HB, started mini counter, pulled lever','no comment
yesterday, Uploaded to TFG, level 1 escape but temperature stable,
pressure lever north']
每个列表项中都有一个字符串
uploaded by SOMEONE
我需要提取SOMEONE
。
但是,如您所见,SOMEONE
:
这是我需要提取的内容:
someone_names = ['TS','AB','RS','DY','KKP','HB','TFG']
我当时在考虑使用正则表达式,但是我面临的问题来自上面的第2点和第3点。
有没有办法从列表中拉出这些字符?
您可以使用列表推导来实现正则表达式。
>>> import re
>>> list_a = [
'temp_52_head sensor, uploaded by TS',
'crack in the left quadrant, uploaded by AB, Left in 2hr sunlight',
'FSL_pressure, uploaded by RS, no reported vacuum',
'art9943_mercury, Uploaded by DY, accelerated, hurst potential too low',
'uploaded by KKP, Space 55',
'avogadro reading level, uploaded by HB, started mini counter, pulled lever',
'no comment yesterday, Uploaded to TFG, level 1 escape but temperature stable,pressure lever north'
]
>>> regex = re.compile(r'(?i)\buploaded\s*(?:by|to)\s*([a-z]{2,3})')
>>> names = [m.group(1) for x in list_a for m in [regex.search(x)] if m]
['TS', 'AB', 'RS', 'DY', 'KKP', 'HB', 'TFG']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句