社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

用python解析json txt文件

iilla • 5 年前 • 1296 次点击  

我有一个txt文件,它在每一行包含json字符串,第一行如下:

{"rating": 9.3, "genres": ["Crime", "Drama"], "rated": "R", "filming_locations": "Ashland, Ohio, USA", "language": ["English"], "title": "The Shawshank Redemption", "runtime": ["142 min"], "poster": "http://img3.douban.com/lpic/s1311361.jpg", "imdb_url": "http://www.imdb.com/title/tt0111161/", "writers": ["Stephen King", "Frank Darabont"], "imdb_id": "tt0111161", "directors": ["Frank Darabont"], "rating_count": 894012, "actors": ["Tim Robbins", "Morgan Freeman", "Bob Gunton", "William Sadler", "Clancy Brown", "Gil Bellows", "Mark Rolston", "James Whitmore", "Jeffrey DeMunn", "Larry Brandenburg", "Neil Giuntoli", "Brian Libby", "David Proval", "Joseph Ragno", "Jude Ciccolella"], "plot_simple": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", "year": 1994, "country": ["USA"], "type": "M", "release_date": 19941014, "also_known_as": ["Die Verurteilten"]}

我想获取IMDB的ID和标题数据。

我试过:

import json
data = json.load('movie_acotrs_data.txt')

但是got'str'对象没有'read'属性

我该怎么做才能得到我期望的结果?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40644
 
1296 次点击  
文章 [ 2 ]  |  最新文章 5 年前
scnerd
Reply   •   1 楼
scnerd    5 年前

json.load 接受打开的文件,而不是文件路径。

data = json.load(open('movie_acotrs_data.txt'))
Barmar
Reply   •   2 楼
Barmar    5 年前

json.load() 期望文件只是一个长的json字符串。如果每行上都是单独的json字符串,则不能使用它。你需要阅读每一行并打电话 json.loads() .

import json
with open('movie_actors_data.txt') as f:
    data = list(map(json.loads, f))

data 将是字典列表。

如果你只想要一些属性,你可以使用列表理解。

with open('movie_actors_data.txt') as f:
    data = [{"title": x["title"], "imdb_id": x["imdb_id"]} for x in map(json.loads, f)]