这是我的代码:
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)
答案 0 :(得分:2)
将jline = json.dumps(line)
更改为jline = json.loads(line)
。
修改强>: 您将拥有以下结构:
{'Title': 'The Shawshank Redemption',
'Year': '1994',
'Rated': 'R',
'Actors': 'Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler'}
然后你可以:
jline2 = {jline['Title']: jline['Actors'].split(', ')}
因此jline2将如下:
{'The Shawshank Redemption': ['Tim Robbins',
'Morgan Freeman',
'Bob Gunton',
'William Sadler'] }
这种结构很容易穿越。