如何在python中使用regex删除一行中的键对并只打印:之后的值

2024-10-03 04:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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'

Tags: textnameamlongcaazmetroips
1条回答
网友
1楼 · 发布于 2024-10-03 04:29:32

我很确定regex不能完全解析字符串文本语法,所以这项工作比这里值得做的更多。考虑使用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'

相关问题 更多 >