如何删除一行中的键对,并在以下后面打印值:在python中使用正则表达式

时间:2017-02-13 14:54:36

标签: python regex concatenation

I am pretty new to python, The text i have is in text file like : 
{u'metro_name': u'Phoenix-Mesa-Glendale, AZ', u'ips': 38060}
{u'metro_name': u'Los Angeles-Long Beach-Glendale, CA  (MSAD)', u'ips': 31100} 

如何仅在Python中打印值并在一行中用$连接它们,即输出:

'Phoenix-Mesa-Glendale, AZ$$38060','Los Angeles-Long Beach-Glendale, CA  (MSAD)$$31100'

1 个答案:

答案 0 :(得分:1)

我非常确定正则表达式无法完全解析字符串文字语法,所以它的工作量超过了它的价值。考虑使用ast.literal_eval将每一行转换为字典。然后,您可以对其值进行任何字符串操作。

import ast
from collections import OrderedDict
dicts = []
with open("data.txt") as file:
    for line in file:
        d = ast.literal_eval(line)
        d = OrderedDict((k, d[k]) for k in ('metro_name', 'ips'))
        dicts.append(d)

output_lines = []
for dict in dicts:
    values = [str(value) for value in dict.values()]
    line = "$$".join(values)
    output_lines.append(repr(line))
print ",".join(output_lines)

结果:

'Phoenix-Mesa-Glendale, AZ$$38060','Los Angeles-Long Beach-Glendale, CA  (MSAD)$$31100'