Python无限循环,if-else语句循环卡在else statement中

2024-05-23 08:06:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者。在编写无限运行的代码时,我使用whiletrue语句。在满足条件之前,代码运行良好。一旦不满足,它只在else语句中循环。请帮忙。在

import sys
import urllib2
import urllib
import re
from urllib import urlopen
import json 
import difflib
import pymysql
import youtube_dl
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import time

rotation_symbols = ['\|', '/', ',', '\+', ';', '_']
re_remparenthesis = re.compile('(.+)\s(\(.+?\))\s*(.*)')

DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

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"]



def remove_parenthesis(s):
    """
    Remove parenthesis, like Thierry (Coolest guy)
    """
    m = re_remparenthesis.match(s)
    if not m:
        return s
    parts = m.groups()
    assert len(parts) >= 2
    if len(parts) == 2:
        return parts[0]
    return parts[0] + ' ' + parts[2]

def replace_rotation_symbols(s):
    """
    Mostly, replace '&' by 'and'
    """
    return re_rotsymbols.sub(' and ', s)

def Normalize(str):
    text=str
    count=text.count('(')
    print(count)
    while count>0:
        text=remove_parenthesis(text)
        count=count-1
    print(text)   
    if ' feat.' in text:
        new_text=text.strip(' feat.')
    elif ' feat' in text:
        new_text=text.strip(' feat')
    elif ' ft' in text:
        new_text=text.strip(' ft')
    elif ' ft.' in text:
        new_text=text.strip(' ft.')
    elif ' featuring' in text:
        new_text=text.strip(' featuring')
    elif ' Starring' in text:
        new_text=text.strip(' Starring')
    elif ' Feat' in text:
        new_text=text.strip(' Feat')
    elif ' Feat.' in text:
        new_text=text.strip(' Feat.')
    elif ' Featuring' in text:
        new_text=text.strip(' Featuring')
    elif ' Ft.' in text:
        new_text=text.strip(' Ft.')
    elif ' starring' in text:
        new_text=text.strip(' starring')
    elif ' vs' in text:
        new_text=text.strip(' vs')
    elif ' vs.' in text:
        new_text=text.strip(' vs.')

    else:
        new_text=text

    print(new_text)
    space_replace=new_text.replace(' ', '%26')

    new_text_2=space_replace.translate(' ' .join(rotation_symbols))
    print(new_text_2)

    if '&' in new_text_2:
        new_text_4=new_text_2.replace('&', '%26')
    else:
        new_text_4=new_text_2
    print(new_text_4)
    return new_text_4

global conn
conn=pymysql.connect(db='Soundcloud_songs', user='root' , host='127.0.0.1' , port=3307)
global cursor
cursor=conn.cursor()
global query
global quer_res
global sc_tid
global line
global text
global youtube
global videoID
global videoTitle
global yt_vid
global perm
global new_text_3
global api_beg
global api_end
global api_final
global html
global result
global iter
global artist
global song_name
global compare_term
global seq
global similarity
global artist_final
global song_final
global analysis_url
global artist_id
global song_id

while True: 
    query=cursor.execute("select SC_TID , SC_Title from Fetched_EN_Analysis where Found_on_en is null order by id asc limit 1")
    if query>0:
        quer_res=cursor.fetchone()
        sc_tid=quer_res[0]
        line=quer_res[1]
        print(sc_tid)
        print(line)
        text=line            
        try:
            youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)
            videoID, videoTitle = search_video(text)
            print("\tFound video: '" + videoTitle + "' - ID: " + videoID)
            yt_vid=videoID
            perm=videoTitle.lower()
        except:
            yt_vid='NA'
            perm=line.lower()
        new_text_3=Normalize(perm)
        api_beg='http://developer.echonest.com/api/v4/song/search?api_key=""&format=json&results=3&combined='
        api_end='&bucket=audio_summary'
        api_final=api_beg + new_text_3 + api_end
        html=urlopen(api_final).read()
        result=json.loads(html)
        iter=0
        for i in result['response']['songs']:
                    print("iteration #", iter+1)
                    iter=iter+1
                    artist=i['artist_name']
                    print(artist)
                    song_name=i['title']
                    print(song_name)
                    compare_term=artist + ' ' + song_name
                    compare_term=compare_term.lower()
                    print(compare_term)
                    seq=difflib.SequenceMatcher(None,compare_term, perm)
                    similarity= seq.ratio()
                    print(similarity)
                    if similarity>0.70:
                        artist_final=artist
                        song_final=song_name
                        analysis_url=i['audio_summary']['analysis_url']
                        artist_id=i['artist_id']
                        song_id=i['id']
                        print(analysis_url)
                        cursor.execute("update Fetched_EN_Analysis set YT_VID=%s, Artist_name=%s , Artist_ID=%s , Song_name=%s , Song_ID=%s , Match_Percent=%s , Analysis_URL=%s , Found_on_en=1 where SC_TID=%s", (yt_vid.encode('utf-8'), artist_final.encode('utf-8') , artist_id.encode('utf-8') , song_final.encode('utf-8') , song_id.encode('utf-8') , similarity, analysis_url.encode('utf-8'), sc_tid))
                        print("query loaded")
                        conn.commit()
                        break
                    else:
                        print("trying next item")
                        cursor.execute("update Fetched_EN_Analysis set Found_on_en=2 where SC_TID=%s", (sc_tid))
                        conn.commit()                 

    else:
        print("No Row left, sleep for 5 mins")
        time.sleep(30)

    continue

Tags: textnameinimportapiidnewsearch

热门问题