• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python song.search函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyechonest.song.search函数的典型用法代码示例。如果您正苦于以下问题:Python search函数的具体用法?Python search怎么用?Python search使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了search函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: getSongInfo

def getSongInfo(s, case):
    res7D = []
    resEN = []

    if case == 1:
        # string contains name of the song
        resEN = song.search(title=s)
        # res7D = py7D.request('track', 'search', q=s, pageSize=1)

        # figure out the artist

    elif case == 2:
        # string contains name of the artist
        resEN = song.search(artist=s)

        # figure out the song

    elif case == 3:
        # string contains song and artist
        resEN = song.search(combined=s)

    if len(resEN) > 0:
        for i in range(0, len(resEN)):
            title = resEN[i].title
            artist_name = resEN[i].artist_name
            print artist_name + " - " + title
        return resEN
    else:
        raise NameError("song not found")
开发者ID:kadrik,项目名称:jubal,代码行数:29,代码来源:en.py


示例2: song_info

def song_info(artist, title):
    if title is u'':
        print("Searching for '%s'" % artist)
        result = song.search(combined=artist)
    else:
        print("Searching for '%s - %s'" % (artist, title))
        result = song.search(artist=artist, title=title)
    print_search_results(take(3, result))
开发者ID:jasalt,项目名称:key-friend,代码行数:8,代码来源:keyfriend.py


示例3: main

def main():
    artists = pickle.load(open("artists.pickle"))
    sys.stdout.write("Building...")
    sys.stdout.flush()

    start = len(artists) / 2 + 350
    for i, artist in enumerate(artists[start:]):
        try:
            songs = song.search(artist_id=artist.id)
        except pyechonest.util.EchoNestAPIError, e:
            sys.stdout.write("XXX")
            sys.stdout.flush()
            continue

        for j, sng in enumerate(songs):
            metadata = get_metadata(sng)
            try:
                segments = get_segments(sng)
            except pyechonest.util.EchoNestAPIError, e:
                time.sleep(30)
                continue

            features = extract_features(segments)
            metadata.update({"features": features})
            col.insert(metadata)
            sys.stdout.write(".")
            sys.stdout.flush()

            if j % 5 == 0:
                sys.stdout.write("zzz")
                sys.stdout.flush()
                time.sleep(2)
开发者ID:jkal,项目名称:sndidx,代码行数:32,代码来源:build_dataset.py


示例4: dance_songs

def dance_songs(artist_id, dance=0.6, maxresults=10):
    results = song.search(artist_id=artist_id,
                          min_danceability=dance,
                          results=maxresults,
                          sort='danceability-desc',
                          buckets=['audio_summary'])
    return results
开发者ID:CosmoGlenns,项目名称:automaticdj,代码行数:7,代码来源:echonest.py


示例5: findTrack

def findTrack():
    track = request.args.get('song', '')
    artist = request.args.get('artist', '')
    filenames = ['TRBIJES12903CF5B12.h5', \
                'TRBIJFB128F92ED124.h5', \
                'TRBIJFO128F42990C5.h5', \
                'TRBIJIA128F425F57D.h5', \
                'TRBIJIP128F9334953.h5', \
                'TRBIJKN12903CBF11B.h5', \
                'TRBIJLT12903CE7070.h5', \
                'TRBIJMU12903CF892B.h5', \
                'TRBIJNF128F14815A7.h5', \
                'TRBIJNK128F93093EC.h5', \
                'TRBIJRN128F425F3DD.h5', \
                'TRBIJYB128F14AE326.h5']
    if track == '' or artist == '':
        return render_template('tracksearch.html',
            searchOk = False,
            filenames = filenames)
    else:
        # Find the requested song with echonest API
        result = song.search(artist = artist, title = track)[0]

        return render_template('tracksearch.html',
            searchOk = True,
            result = result,
            filenames = filenames)
开发者ID:adlenafane,项目名称:ML,代码行数:27,代码来源:views.py


示例6: lookup_track

def lookup_track(album, metadata, release, track):
    tagger = album.tagger
    upload = tagger.config.setting["echonest_upload"]
    artist_title_lookup = tagger.config.setting["echonest_artist_title_lookup"]
    songs = []
    try:
      songs = echosong.profile([u"musicbrainz:song:%s" % metadata['musicbrainz_trackid']],
          buckets="audio_summary")
    except EchoNestAPIError:
      if artist_title_lookup:
        songs = echosong.search(title=metadata['title'], artist=metadata['artist'])
    min_diff = tagger.config.setting["echonest_duration_diff"]
    match = None
    for song in songs:
        # try to match based on duration / length
        len_diff = abs(metadata.length / 1000.0 - song.audio_summary['duration'])
        if min_diff < 0.0 or len_diff < min_diff:
            min_diff = len_diff
            match = song
    if match:
        metadata['bpm'] = str(match.audio_summary['tempo'])
        metadata['comment:Songs-DB_Energy'] = str(match.audio_summary['energy'])
        metadata['comment:Songs-DB_Danceability'] = str(match.audio_summary['danceability'])
    elif upload:
        # FIXME:  how do i get the filename for this track?
        pass
    req_minus(album)
开发者ID:pscn,项目名称:echonest,代码行数:27,代码来源:__init__.py


示例7: fetch_track

def fetch_track(track_params):
    """
    Fetch a track from 7digital via the Echo Nest API.

    Available track parameters are listed at
    http://developer.echonest.com/docs/v4/song.html#search
    """
    try:
        search_results = echonest_song.search(
            buckets=['id:7digital-US', 'tracks'],
            limit=True,
            results=app.config['ECHO_NEST_SONG_RESULTS'],
            **track_params
        )
    except TypeError as exc:
        raise GweetrError("Received unknown track parameter: %s" % str(exc))

    if search_results:
        song_obj = random.choice(search_results)
        tracks = song_obj.get_tracks('7digital-US')
        track_data = tracks[0]
        track = {
            'title': song_obj.title,
            'artist': song_obj.artist_name,
            'url': track_data['preview_url']
        }
        return track
开发者ID:Sushant,项目名称:gweetr,代码行数:27,代码来源:utils.py


示例8: get_from_spotify

    def get_from_spotify(artist, title):
        # Getting data from spotify
        request_url = '{}/search'.format(SPOTIFY_API)
        query = '{} {}'.format(artist, title)
        response = requests.get(request_url, params={'q': query, 'type': 'track'}).json()

        items = response['tracks']['items']
        if not items:
            print "Couldn't find '{} - {}' on Spotify".format(artist, title)
            return None
        raw_track_data = items[0]

        track_data = dict()
        for attr in ['id', 'name', 'uri', 'preview_url']:
            track_data[attr] = raw_track_data[attr]
        track_data['artist_name'] = raw_track_data['artists'][0]['name']
        track_data['artist_id'] = raw_track_data['artists'][0]['id']
        track_data['album'] = raw_track_data['album']['name']
        track_data['image'] = raw_track_data['album']['images'][0]['url']

        # EchoNest enrichement
        songs = echonest_song.search(artist=artist, title=title)
        if not songs:
            print "Couldn't find '{} - {}' on EchoNest".format(artist, title)
            return None
        song = songs[0]
        track_data['audio_summary'] = song.audio_summary
        artist = echonest_artist.search(name=song.artist_name)[0]
        track_data['genres'] = [t['name'] for t in artist.terms]

        return Track(**track_data)
开发者ID:diversify,项目名称:beautiful-world,代码行数:31,代码来源:models.py


示例9: categorize_tweets_csv

def categorize_tweets_csv():
    for tweetsfile in os.listdir(os.getcwd()):
        excitements = []
        happy = 0
        exclamations = 0
        counter_num = 0
        if tweetsfile.endswith(".csv"):
            print tweetsfile
            with open(tweetsfile, 'r') as csvfile:
                csvreader = csv.reader(csvfile)
                for tweet, sentiment, accuracy in csvreader:
                    counter_num += 1
                    if sentiment == "positive" and accuracy >= 50:
                        happy += 1
                    if tweet.count("!") > 1 and tweet.count(".") <= 1:
                       exclamations += 1

            exclamation_percentage = exclamations / float(counter_num)
            # excitement = (sum(excitements) + exclamations) / float(len(excitements))
            happy /= float(counter_num)
            if exclamation_percentage > .15:
                if happy > .4:
                    mood = "happy"
                else:
                    mood = "angry"
            else:
                if happy > .4:
                    mood = "relaxed"
                else:
                    mood = "sad"
            rkp_results = song.search(mood=mood, min_energy=exclamation_percentage, artist_min_familiarity=.6, style="pop", artist_start_year_after="1999")
            resultant_song = rkp_results[0]
            print resultant_song.title + " - " + resultant_song.artist_name + " happy " + str(happy) + " excite " + str(exclamation_percentage)
开发者ID:jakew32,项目名称:bitcamp15,代码行数:33,代码来源:logic.py


示例10: _similar_tracks

 def _similar_tracks(self, callback, artist, title, threshold):
   timestamp = now()
   diff = timestamp - self.get_track_timestamp(artist, title)
   if diff < threshold:
     self._logger.debug(u"similar_tracks[%s-%s]: looked up %d seconds ago" %
         (artist, title, diff))
     return
   self.set_track_timestamp(artist, title, timestamp)
   try:
     self._logger.debug(u"similar_tracks[%s-%s]: lookup" % (artist, title))
     self._delay()
     a = en_song.search(title=title, artist=artist)
     try:
       p = en_playlist.static(type='song-radio', song_id=a[0].id, results=100)
       i = 100.0
       self._logger.info(u"similar_tracks[%s-%s]: %d result(s)" % (artist,
           title, len(p)))
       for song in p:
         callback(artist, title, song.artist_name.lower(), song.title.lower(),
             i / 100.0, self._title)
         i -= 1.0
     except IndexError:
       self._logger.info(u"similar_tracks[%s-%s]: no result" % (artist, title))
       return
   except Exception, e:
     self._logger.error(e)
     self._logger.info(u"similar_tracks[%s-%s]: no result" % (artist, title))
     return
开发者ID:pscn,项目名称:ads,代码行数:28,代码来源:lookup_echonest.py


示例11: get_tempo

def get_tempo(artist, title):
    "gets the tempo for a song"
    results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary'])
    if len(results) > 0:
        return results[0].audio_summary['tempo']
    else:
        return None
开发者ID:wesclemens,项目名称:pyechonest,代码行数:7,代码来源:tempo.py


示例12: get_echonest_metadata

def get_echonest_metadata(search_terms, spotify_uris):
    buckets = [
        'audio_summary',
        'artist_discovery',
        'artist_familiarity',
        'artist_hotttnesss',
        'artist_location',
        'song_discovery',
        'song_hotttnesss',
    ]
    try:
        s = song.search(
            artist=search_terms['a'],
            title=search_terms['t'],
            buckets=buckets,
        )[0]
    except IndexError:
        sys.stdout.write("  Falling back to uri lookup\n")
        try:
            s = song.profile(
                track_ids=spotify_uris,
                buckets=buckets
            )[0]
        except EchoNestAPIError:
            sys.stdout.write("  Failed to find echonest metadata\n")
            return []
    return json.dumps(s.__dict__)
开发者ID:exonian,项目名称:playviz,代码行数:27,代码来源:fetch_metadata.py


示例13: plot

 def plot(self):
     """Plot song data"""
     songs = echosong.search(title=self.title, artist=self.artist, results=1)
     if songs:
         # Search for the track through all catalogues
         for catalog in CATALOGS:
             # Fails when the API Key can't access a catalogue
             try:
                 tracks = songs[0].get_tracks(catalog)
             except EchoNestAPIError:
                 continue
             # Get track or go to next catalogue
             if not tracks:
                 continue
             track = echotrack.track_from_id(tracks[0]['id'])
             # Adjust start and end
             self.start = self.start < track.duration and self.start or 0
             self.end = self.end < track.duration and self.end or track.duration
             # Get full aoustic analysis
             track.get_analysis()
             # Loudness (from segments)
             x = np.array([segment.get('start') for segment in track.segments if self._inrange(segment)])
             y = np.array([segment.get('loudness_max') for segment in track.segments if self._inrange(segment)])
             plt.plot(x, y)
             plt.xlabel('Duration')
             plt.ylabel('Loudness')
             # Use sections as a grid
             [plt.axvline(section.get('start')+section.get('duration'), color='k', linestyle='--') for section in track.sections]
             # Add caption and show plot
             plt.suptitle('%s - %s' %(self.artist, self.title))
             plt.show()
             return
开发者ID:apassant,项目名称:echoplot,代码行数:32,代码来源:echoplot.py


示例14: get_tempo

def get_tempo(artist, title):
    "gets the tempo for a song"
    results = song.search(artist=artist, title=title, results=1, buckets=buckets)
    if len(results['response']['songs']) > 0:
        return results['response']['songs'][0]
    else:
        return None
开发者ID:hanshanqui,项目名称:MusicML,代码行数:7,代码来源:fetchEchoNest.py


示例15: dump

def dump(file):
	dictionary = {}
	failedList = []
	with open("parsedHits.csv") as csv_file:
		i=0;
		for row in csv.reader(csv_file, delimiter=','):
				print i
				i=i+1
				sleep(3)
				#total = int(col)
				songArtist = row[2]
				songName = row[1]
				print "getting hits:%s from %s"%(songName,songArtist)
				startTime = time.time()
				record=song.search(artist = songArtist, title=songName)
				endTime  = time.time()
				print "time for api call was: %s ms"%(endTime - startTime)
				if record:
					dictionary[songName]=record[0]
					#dictionary[songName]=record[0].audio_summary['tempo']
					print "song name: %s , %s "%(songName,record[0].audio_summary)
				else:
					failedList.append([songArtist,songName])
				if(i>60):
					sleep(60)
					i=0;
	#print dictionary

	pickle.dump(failedList, open(failed.p,"wb")) 
	pickle.dump( dictionary, open( file+".p", "wb" ) ) 

	print "printing failedList..."
	for i in failedList:
		print i
	print "printed failedList..."
开发者ID:jakdemir,项目名称:big_beat,代码行数:35,代码来源:get-beat.py


示例16: get_song

def get_song(combined="kreayshawn gucci gucci"):
    s = song.search(combined=combined,buckets=["id:7digital-US","tracks"],limit=True,results=1)
    if len(s) > 0:
        try:
            url = s[0].get_tracks("7digital-US")[0]["preview_url"]
            return (url, s[0])
        except KeyError:
            return (None, None)
开发者ID:echonest,项目名称:snuGIFy,代码行数:8,代码来源:looper.py


示例17: check_song

def check_song(artist, title):
    res = song.search(artist=artist, title=title)
    if res:
        meta = res[0].audio_summary # HAAAAAACKS
        display_metadata("{0} - {1}".format(artist, title),
                         meta['tempo'],
                         meta['key'],
                         meta['mode'])
开发者ID:kingcons,项目名称:hacks,代码行数:8,代码来源:mix_help.py


示例18: get_songs

def get_songs(name):
    # get 50 hottest songs for each artist to use as chapter headings
    song_titles = []
    songs = en_song.search(artist=name,results=50,sort='song_hotttnesss-desc')
    for song in songs:
        if song.title not in song_titles:
            song_titles.append(song.title)
    return song_titles
开发者ID:bowilliams,项目名称:secret-history,代码行数:8,代码来源:wordmapper.py


示例19: song_search

def song_search():
    songs = song.search(min_tempo=120, max_tempo=160, artist_start_year_after=1980,
                        artist_end_year_before=2000, min_danceability=0.6,
                        artist_min_familiarity=0.5, buckets=["id:spotify-WW", "tracks"])
    for s in songs:
        print s.title, "by", s.artist_name
        for t in s.get_tracks("spotify-WW"):
            uri = t["foreign_id"].replace("spotify-WW", "spotify")
            print " ", uri
开发者ID:dotpot,项目名称:ep2013,代码行数:9,代码来源:echonest_demo.py


示例20: get_lyricfind_ids

def get_lyricfind_ids(artist=None, title=None, genre=None, num_songs=1):
    if genre:
        res = playlist.static(results=num_songs,type='genre-radio',genres=genre,buckets=['id:lyricfind-US'], limit=True)
    elif not title:
        res = playlist.static(results=num_songs,type='artist',artist=artist,buckets=['id:lyricfind-US'], limit=True)
    else:
        res = song.search(sort='song_hotttnesss-desc', buckets=['id:lyricfind-US'], limit=True, artist=artist, title=title, results=num_songs)
    lids = [x.get_foreign_id('lyricfind-US').split(":")[-1] for x in res]
    print [x for x in lids]
开发者ID:markaurelius,项目名称:verbquest,代码行数:9,代码来源:gather_verbs.py



注:本文中的pyechonest.song.search函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python ec_iface.ECDriver类代码示例发布时间:2022-05-25
下一篇:
Python pyecharts.Line类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap