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'
答案 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'