0

我制作了这个 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?

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

谢谢!

4

1 回答 1

0

您读取和写入Binary mode最可能不想要的文件。打开读取文件为"U",写入文件为"w".

于 2013-09-11T06:21:11.713 回答