这个Echonest API调用的Python代码有什么问题?

时间:2013-09-11 04:17:39

标签: python json api csv

我制作了这个Python脚本,尝试使用CSV文件中的一堆歌曲ID代码查询Echonest Songs API,并将JSON响应解析为新的CSV文件。

我从中拉出的CSV只有一列加上标题; JSON响应如下所示(id值是CSV中的值):

{

    "response": {
        "status": {
            "version": "4.2",
            "code": 0,
            "message": "Success"
        },
        "songs": [
            {
                "artist_id": "ARSQSCB1187B9912A0",
                "artist_name": "Warren G",
                "id": "SOCHNQM13167710571",
                "audio_summary": {
                    "key": 11,
                    "analysis_url": "http://echonest-analysis.s3.amazonaws.com/TR/46UlqAq8HVkiQEZM0TBRYS2f9FihdJTqhIjeBh/3/full.json?AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ&Expires=1378873388&Signature=mXiI%2Bb%2BndmJMiIl9GNPO8GEDT08%3D",
                    "energy": 0.34873219698986957,
                    "liveness": 0.2955813703355687,
                    "tempo": 95.315,
                    "speechiness": 0.3528227641100349,
                    "acousticness": 0.6892753604056542,
                    "mode": 0,
                    "time_signature": 4,
                    "duration": 232.45333,
                    "loudness": -8.597,
                    "audio_md5": "b7eca18e4ac88f97f188007f45fe8daa",
                    "valence": 0.6579951690603227,
                    "danceability": 0.8058721228042193
                },
                "title": "Make It Do What It Do"
            }
        ]
    }

}

到目前为止,这是我的Python脚本:

#!/Users/.../anaconda/bin/Python

import urllib
import json
import csv
from time import sleep
API_URL = 'http://developer.echonest.com/api/v4/song/profile?'
API_KEY = 'api_key here'
writer = csv.writer(open("/Users/me/path/to/output", "wB"))
input_file = csv.DictReader(open('/me/path/to/input', "rB"))
for row in input_file:
  song_id = row['id']
  qs = urllib.urlencode({"api_key": API_KEY,
                         "bucket": "audio_summary",
                         "id": song_id})
  url = '{}?{}'.format(API_URL, qs)
  resource = urllib.urlopen(url)
  parsed_json = json.load(resource)
  for songs in parsed_json:
    print songs
    row = []
    writer.writerow({k: v.encode('utf-8') for k, v in songs.audio_summary()})
    sleep(5)

当我尝试从命令行运行脚本时,我收到这些错误:

Traceback (most recent call last):
  File "/Users/.../Rap/echo.py", line 11, in <module>
    for row in input_file:
  File "/Users/.../anaconda/lib/python2.7/csv.py", line 103, in next
    self.fieldnames
  File "/Users/.../anaconda/lib/python2.7/csv.py", line 90, in fieldnames
    self._fieldnames = self.reader.next()
_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

我对编程很陌生 - 我的脚本中有什么需要修复的吗?有更好的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您在Binary mode中读取和写入的文件很可能不是您想要的。将阅读文件打开为"U",将文件打开为"w"