0
我正在編寫一個程序來讀取一首歌曲的mysql表格,並在youtube上找到該歌曲。我想下載該歌曲並將其放在我的soundcloud帳戶上。我試圖爲此編寫代碼。問題是,我每次運行它的時候,我得到了以下問題:編碼問題-python
Non-ASCII character '\xe2' in file on line 164, but no encoding declared
請幫助解決一樣。
import youtube_dl
from apiclient.discovery import build
from apiclient.errors import HttpError
import sys
import pymysql
import urllib2
import urllib
from urllib import urlopen
import json
import soundcloud
from goto import goto, label
import time
DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
global conn
conn=pymysql.connect(db='twitter_users', user='root' , host='127.0.0.1' , port=3307)
global cursor
cursor=conn.cursor()
client = soundcloud.Client(client_id= '',
client_secret= '',
username= '',
password= '')
global song_name
global artist_final
global stored_title
global genre
def search_video(title):
search_response = youtube.search().list(
q=title,
part="id,snippet",
maxResults=10
).execute()
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
return search_result["id"]["videoId"], search_result["snippet"]["title"]
##youtube_dl configuration
class MyLogger(object):
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self, msg):
print(msg)
def my_hook(d):
if d['status'] == 'downloading':
sys.stdout.write('\r\033[K')
sys.stdout.write('\tDownloading... ETA: ' + str(d["eta"]) + " seconds")
sys.stdout.flush()
elif d['status'] == 'finished':
sys.stdout.write('\r\033[K')
sys.stdout.write('\tDownload complete\n\tConverting video to mp3')
sys.stdout.flush()
ydl_opts = {
'format': 'bestaudio',
'outtmpl': '%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '0',
}],
'logger': MyLogger(),
'progress_hooks': [my_hook],
}
##main
label .start
if __name__ == "__main__":
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)
query=cursor.execute("select search_term from song_downloads where Soundcloud_TID='' order by id asc limit 1")
if query>0:
query_result=cursor.fetchone()
term=query_result[0]
else:
goto .end
print("\tSearching video")
try:
videoID, videoTitle = search_video(term);
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
print("\tFound video: '" + videoTitle + "' - ID: " + videoID)
Find=cursor.execute("select Youtube_VID from song_downloads where Youtube_VID=%s", (videoID))
if find>0:
goto .duplicate
else:
try:
song_name=videoTitle.split(' - ')[1]
except:
song_name='Null'
try:
Artist_name=videoTitle.split(' - ')[0]
if ' feat. ' in Artist_name:
artist_final=Artist_name.split(' feat. ')[0]
elif ' feat ' in Artist_name:
artist_final=Artist_name.split(' feat ')[0]
elif ' ft ' in Artist_name:
artist_final=Artist_name.split(' ft ')[0]
elif ' ft. ' in Artist_name:
artist_final=Artist_name.split(' ft. ')[0]
elif ' featuring ' in Artist_name:
artist_final=Artist_name.split(' featuring ')[0]
elif ' Starring ' in Artist_name:
artist_final=Artist_name.split(' Starring ')[0]
elif ' Feat ' in Artist_name:
artist_final=Artist_name.split(' Feat ')[0]
elif ' Feat. ' in Artist_name:
artist_final=Artist_name.split(' Feat.')[0]
elif ' Featuring ' in Artist_name:
artist_final=Artist_name.split(' Featuring ')[0]
elif ' Ft. ' in Artist_name:
artist_final=Artist_name.split(' Ft. ')[0]
elif ' starring ' in Artist_name:
artist_final=Artist_name.split(' starring ')[0]
else:
artist_final=Artist_name
except:
artist_final='Null'
if artist_final=='Null':
genre='Null'
else:
try:
api_beg='http://developer.echonest.com/api/v4/artist/profile?api_key=OZ8G9N2O7YFPZIRXN&'
api_end='&bucket=genre&format=json'
api_final=api_beg+'name='+artist_final+api_end
url= urlopen(api_final).read()
print('url read')
result=json.loads(url)
print('result decoded')
genre= result['response']['artist']['genres'][0]['name']
except:
genre='Null'
if artist_final=='Null':
album_art='Null'
else:
try:
api_image_beg='http://developer.echonest.com/api/v4/song/search?api_key=OZ8G9N2O7YFPZIRXN&format=json&results=1&artist='
api_image_end='&bucket=id:7digital-US&bucket=tracks'
api_image_final=api_image_beg+artist_final+'&title='+song_name+api_image_end
url= urlopen(api_image_final).read()
result=json.loads(url)
album_art=result['response']['songs'][0]['tracks'][0]['release_image']
print(album_art)
except:
album_art='Null'
print(artist_final)
print(genre)
ydl.download(['http://www.youtube.com/watch?v=' + videoID])
print("\tDone")
stored_title=videoTitle + '.mp3'
cursor.execute("update song_downloads set Song_Name=%s , Artist_Name=%s, Genre=%s, Album_art_url=%s, Youtube_VID=%s, video_title=%s where Search_Term=%s" , (song_name.encode('utf-8'), artist_final('utf-8'), genre.encode('utf-8'),album_art.encode(‘utf-8’),videoID.encode('utf-8'),stored_title.encode('utf-8'), term.encode('utf-8')))
conn.commit()
track = client.post('/tracks', track={
'title': song_name + '-' artist_final,
'genre': genre,
'artwork_data':album_art,
'asset_data': open(stored_title, 'rb')
})
soundcloud_track_url=track.permalink_url
cursor.execute("update song_downloads set Soundcloud_TID=%s where Youtube_VID=%s" , (soundcloud_track_url.encode('utf-8'),videoID.encode('utf-8')))
conn.commit()
print("Track downloaded and posted to SC")
label .duplicate
cursor.execute("update song_downloads set Youtube_VID='duplicate' where Search_Term=%s " , (term))
label .end
print("sleep for 1 minute")
time.sleep(60)
goto .start
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
[Python「SyntaxError:文件」中的非ASCII字符'\ xe2']的可能重複(http://stackoverflow.com/questions/21639275/python-syntaxerror-non-ascii-character-xe2-in-文件) –
對不起,我沒有時間仔細查看你的代碼,但這很可能是unicode的問題。您可能需要在某處編碼一個unicode字符串,可能只需使用'string.encode'('utf8','replace')'。看看這裏:https://pythonhosted.org/kitchen/unicode-frustrations.html。 –
就這麼你知道,我在'cursor.execute'行看到一個錯誤,你只需要'artist_final('utf-8')''這需要'artist_final.encode'('utf-8')'。 – CasualDemon