我真的很接近拥有一个从纽约时报 API 获取 JSON,然后将其转换为 CSV 的脚本。但是,有时我会收到此错误:
UnicodeEncodeError:“ascii”编解码器无法在位置 21 编码字符 u'\u201c':序数不在范围内(128)
如果我将输出转换为 UTF-8,我想我可以避免这一切,但我不确定如何去做。这是我的python脚本:
import urllib2
import json
import csv
outfile_path='/NYTComments.csv'
writer = csv.writer(open(outfile_path, 'w'))
url = urllib2.Request('http://api.nytimes.com/svc/community/v2/comments/recent?api-key=ea7aac6c5d0723d7f1e06c8035d27305:5:66594855')
parsed_json = json.load(urllib2.urlopen(url))
print parsed_json
for comment in parsed_json['results']['comments']:
row = []
row.append(str(comment['commentSequence']))
row.append(str(comment['commentBody']))
row.append(str(comment['commentTitle']))
row.append(str(comment['approveDate']))
writer.writerow(row)