python - 通过正则表达式修改字符串列表

时间:2016-01-27 12:30:13

标签: python regex string list list-comprehension

我有一个字符串列表

query_var = ["VENUE_CITY_NAME == 'Bangalore' & EVENT_GENRE == 'ROMANCE' & count_EVENT_GENRE >= 1","VENUE_CITY_NAME == 'Jamshedpur' & EVENT_GENRE == 'HORROR' & count_EVENT_GENRE >= 1"]
len(query_var)   #o/p 2

我想修改此列表以获取

 query_var = ["df['VENUE_CITY_NAME'] == 'Bangalore' & df['EVENT_GENRE'] == 'ROMANCE' & df['count_EVENT_GENRE'] >= 1","df['VENUE_CITY_NAME'] == 'Jamshedpur' & df['EVENT_GENRE'] == 'HORROR' & df['count_EVENT_GENRE'] >= 1"]

这是我的尝试:

for res in query_var:
    res = [x for x in re.split('[&)]',res)]
    print(res)
    res =  [x.strip() for x in res]
    print(res)
    res = [d.replace(d.split(' ', 1)[0], "df['"+d.split(' ', 1)[0]+"']") for d in res]
    print(res)

产生输出:

 ["VENUE_CITY_NAME == 'Bangalore' ", " EVENT_GENRE == 'ROMANCE' ", ' count_EVENT_GENRE >= 1']
 ["VENUE_CITY_NAME == 'Bangalore'", "EVENT_GENRE == 'ROMANCE'", 'count_EVENT_GENRE >= 1']
 ["df['VENUE_CITY_NAME'] == 'Bangalore'", "df['EVENT_GENRE'] == 'ROMANCE'", "df['count_EVENT_GENRE'] >= 1"]
 ["VENUE_CITY_NAME == 'Jamshedpur' ", " EVENT_GENRE == 'HORROR' ", ' count_EVENT_GENRE >= 1']
 ["VENUE_CITY_NAME == 'Jamshedpur'", "EVENT_GENRE == 'HORROR'", 'count_EVENT_GENRE >= 1']
 ["df['VENUE_CITY_NAME'] == 'Jamshedpur'", "df['EVENT_GENRE'] == 'HORROR'", "df['count_EVENT_GENRE'] >= 1"]

正如预期的那样,但是当我打印query_var时,它没有被更改

query_var
Out[47]: 
   ["VENUE_CITY_NAME == 'Bangalore' & EVENT_GENRE == 'ROMANCE' & count_EVENT_GENRE >= 1","VENUE_CITY_NAME == 'Jamshedpur' & EVENT_GENRE == 'HORROR' & count_EVENT_GENRE >= 1"]

正如您所看到的,我的代码无法生成所需的输出。有没有更好的方法,例如列表理解?

1 个答案:

答案 0 :(得分:3)

这是一个正则表达式/列表解析解决方案:

>>> [re.sub('(\w+)\s*(==|>=)', r"df['\1'] \2", s) for s in query_var]
["df['VENUE_CITY_NAME'] == 'Bangalore' & df['EVENT_GENRE'] == 'ROMANCE' & df['count_EVENT_GENRE'] >= 1", "df['VENUE_CITY_NAME'] == 'Jamshedpur' & df['EVENT_GENRE'] == 'HORROR' & df['count_EVENT_GENRE'] >= 1"]

根据需要调整更多一般数据,例如允许'< ='等。

编辑以回复评论:

[re.sub('(\w+)(\s*(==|>=).*?)(\s*&|$)', r"(df['\1']\2)\4", s) for s in query_var]