【问题标题】:Dump a JSON file and then save to lists转储 JSON 文件,然后保存到列表
【发布时间】: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


【解决方案1】:

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'] }

而且这种结构很容易遍历。

【讨论】:

  • 问题是我想搜索数据并提取值和键。如果我使用 json.loads ,那么我将无法通过它进行搜索并单独拉出演员,演员只是成为一个长字符串。
  • 谢谢,我设法做到了:jline2 = {jline['Title']+'\t['+jline['"'+'Actor'+'"']+']'+'\n' 它给了我围绕一组演员的报价,但不是围绕每个演员。我最终做了我在编辑中发布的内容。
猜你喜欢
  • 2012-03-10
  • 2013-07-07
  • 2021-08-29
  • 2020-09-23
  • 2020-07-13
  • 2021-11-11
  • 2012-03-16
  • 1970-01-01
相关资源
最近更新 更多