繁体   English   中英

使用正则表达式删除python中括号中的内容

[英]Use regular expression to remove contents in brackets in python

我有一个list

['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']

也作为字符串'14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\\n'

使用正则表达式,如何返回:

['14147618', '6137776, '5943229', 2066613']

您根本不需要RegEx,只需使用此列表理解功能,就可以过滤出仅包含数字的数据

print [item for item in data if item.isdigit()]
# ['14147618', '6137776', '5943229', '2066613']

或者您也可以使用filter内置函数,例如

print filter(str.isdigit, data)
# ['14147618', '6137776', '5943229', '2066613']

编辑:如果您将整个数据作为单个字符串,则可以根据空格字符拆分数据,然后使用相同的逻辑

data = '14147618 (100%)   6137776 (43%)   5943229 (42%)   2066613 (14%)  TOTAL\n'
print [item for item in data.split() if item.isdigit()]
# ['14147618', '6137776', '5943229', '2066613']
print filter(str.isdigit, data.split())
# ['14147618', '6137776', '5943229', '2066613']

正如@thefourtheye所说,根本不需要使用正则表达式,但是如果您真的想使用正则表达式,则可以使用:

import re

a = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
result = []

for e in a:
    m = re.match(r'\d+', e)
    if m is not None:
        result.append(e)

print result
# ['14147618', '6137776', '5943229', '2066613']

注意:这也可以写成列表理解:

print [e for e in a if re.match(r'\d+', e)]

这是一种方法:

>>> l = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
>>> [el for el in l if re.match(r'\d+$', el)]
['14147618', '6137776', '5943229', '2066613']

使用re模块:

>>> import re
>>> [item for item in s if re.match(r'\d+',item)]
['14147618', '6137776', '5943229', '2066613']

完全不需要使用re模块,可以在list使用filter

尝试这个 ,

>>> a=['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
>>> filter(str.isdigit, a)
['14147618', '6137776', '5943229', '2066613']
>>>

或者,如果要除最后一个元素外的偶数索引元素:

print [data[i] for i in range(0,len(data)-1,2)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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