【发布时间】:2018-07-27 22:32:17
【问题描述】:
我正在处理一个 python 文件,该文件从 JSON 文件中提取电影及其详细信息,然后将数据保存到自定义电影对象中。现在,我可以从庞大的列表中选择一部电影。
但是,我希望能够遍历并获取每个流派、导演、演员,并将它们添加到单独的数组中。现在当我尝试这样做时,我得到了这个错误:
Traceback (most recent call last):
File "/Users/leoconnelly/PycharmProjects/MLFinal/tester.py", line 27, in <module>
tempGenre = (contents['results'][i]['genre'])
TypeError: list indices must be integers or slices, not str
我还想创建一个包含标题、演员、导演和类型的自定义电影对象的数组。
我的代码如下所示:
from movie import Movie
from user import User
import json
from pprint import pprint
movieArray = []
nameArray = []
directorArray = []
genreArray = []
##actorArray = []
movieToBeInputted = Movie("","","","")
with open('movies.json') as f:
contents = json.load(f)
print(contents['results'][600]['title'])
movieToBeInputted.name = (contents['results'][600]['title'])
movieToBeInputted.director = (contents['results'][600]['director'])
movieToBeInputted.genre = (contents['results'][600]['genre'])
movieToBeInputted.actors = (contents['results'][600]['cast'])
movieArray.append(movieToBeInputted)
for i in contents:
tempGenre = (contents['results'][i]['genre'])
genreArray.append(tempGenre) #this is where the error happens
print("xxxxxxx")
print(movieToBeInputted.actors)
##d = json.load(json_data)
##json_movie_data = json.dumps(json_data)
##movieToBeInputted.actors = json_movie_data
这是我的 json 数据:
{
"results": [
{
"title": "After Dark in Central Park",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Boarding School Girls' Pajama Parade",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Buffalo Bill's Wild West Parad",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Caught",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Clowns Spinning Hats",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Capture of Boer Battery by British",
"year": 1900,
"director": "James H. White",
"cast": null,
"genre": "Short documentary",
"notes": null
},
{
"title": "The Enchanted Drawing",
"year": 1900,
"director": "J. Stuart Blackton",
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Family Troubles",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "Feeding Sea Lions",
"year": 1900,
"director": null,
"cast": "Paul Boyton",
"genre": null,
"notes": null
},
{
"title": "How to Make a Fat Wife Out of Two Lean Ones",
"year": 1900,
"director": null,
"cast": null,
"genre": "Comedy",
"notes": null
},
{
"title": "New Life Rescue",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
},
{
"title": "New Morning Bath",
"year": 1900,
"director": null,
"cast": null,
"genre": null,
"notes": null
}
]
}
【问题讨论】:
-
contents是一本字典...你希望for i in contents是什么?