【发布时间】:2014-02-11 22:41:51
【问题描述】:
这是我的代码:
with open('step3_desired_output.txt') as f, open('jout.txt', 'w') as fout:
for line in f:
jline = json.dumps(line)
#jline2 = jline['Title']+'\t['+jline['"'+'Actor'+'"']+']'+'\n'
print jline2
我将一个 JSON 文件转储到 Python 中,然后我想将一些值组合成字符串。稍后我将使用 pydot 解析文件。
将json数据转储到python中的字符串(jline变量)后,输出如下:
"{\"Title\":\"The Shawshank Redemption\",\"Year\":\"1994\",\"Rated\":\"R\",\"Actors\":\"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\"Plot\":
有多个这样的行。我想将每一行的 Title 和前 4 个 Actor 值输出到一个文本文件中,如下所示:
Title ["Actor","Actor","Actor","Actor"]
输出是 TypeError:字符串索引必须是整数,而不是 str
更新 最后我换了一个方向,做了这个:
file = open('step3_desired_output.txt','rU')
nfile = codecs.open('step4.txt','w','utf-8')
movie_actors = []
for line in file:
line = line.rstrip()
movie = json.loads(line)
l = []
title = movie['Title']
actors = movie['Actors']
tempactorslist = actors.split(',')
actorslist = []
for actor in tempactorslist:
actor = actor.strip()
actorslist.append(actor)
l.append(title)
l.append(actorslist)
row = l[0] + '\t' + json.dumps(l[1]) + '\n'
nfile.writelines(row)
【问题讨论】:
-
谢谢...我认为现在是正确的,我的代码就是这样
-
json.dumps接受一个Python对象(list, string.dict)并生成一个JSON字符串。loads将 JSON 格式的字符串转换为 Python。jline是 JSON 字符串,而不是 Python。line['Title']适用于 Python 字典,而不是字符串。 -
哦,好的,你知道我如何将 jline 中的数据提取成我正在寻找的格式吗?
标签: python json string parsing