我应该如何编写方法从通过JSON搜索后得到的结果中获取“link”值?

2024-03-29 02:32:45 发布

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

一个Python初学者。 我试图找出如何编写一个方法,在搜索歌曲标题或对列表排序后获取“link”值,并让它播放。比如说,我会输入“Hurt”这个词,它会告诉我找到了。我遇到的问题是试图获得它的链接并打开Youtube网站。Json文件的加载非常好。我只需要找出搜索后的下一步。你知道吗

Json文件是:

{"LinkCollection":

[{"title":"I Will Always Love You" , 
"artist":"Whitney Houston" ,
"link":"http://www.youtube.com/watch?v=3JWTaaS7LdU", 
"id":1},

{"title":"Killing Me Softly" , 
"artist":"Roberta Flack" ,
"link":"http://www.youtube.com/watch?v=LQ2t5e7stVM", 
"id":2},

{"title":"Hero" , 
"artist":"Mariah Carey" ,
"link":"http://www.youtube.com/watch?v=0IA3ZvCkRkQ", 
"id":3},

{"title":"Hurt" , 
"artist":"Christina Aguliera" ,
"link":"http://www.youtube.com/watch?v=wwCykGDEp7M", 
"id":4},

{"title":"At Last" , 
"artist":"Etta James" ,
"link":"http://www.youtube.com/watch?v=S-cbOl96RFM", 
"id":5}
]}

课程是:

from pprint import pprint
import json
import operator
from operator import itemgetter
import webbrowser

dataFile = "Music_Database.json"

class MusicLink():

    def __init__(self):
        print "Karaoke"

    def loadData(self,dataFile):
        musicObject = []
        json_data=open(dataFile)
        musicObject = json.load(json_data)
        json_data.close()
        return musicObject

    def searchSong(self,search):
        foundList = []
        musicObject=[]
        musicObject =self.loadData(dataFile)
        #pprint(musicObject["LinkCollection"])
        howmanySongs = len(musicObject["LinkCollection"])
        print "You have %s stored online" %  howmanySongs
        for counter in range(howmanySongs):
            print musicObject["LinkCollection"][counter]["title"]
            name = musicObject["LinkCollection"][counter]["title"].lower()
            print " ."  # show this when you start a new record
            lowerCaseSearch = search.lower() 
            didIfindIt =  name.find( lowerCaseSearch) 
            print didIfindIt
            if didIfindIt >= 0 :
                print "*" # show this when you find it
                foundList.append( musicObject["LinkCollection"][counter]) 
        return foundList

    def sortByTitle(self,foundMedia):
        sortedTitleList = []
        sortedTitleList = sorted(foundMedia, key=itemgetter('title'))
        return sortedTitleList

    def sortByArtist(self,foundMedia):
        print"here"
        pprint(foundMedia)
        sortedByArtistList = []
        sortedByArtistList = sorted(foundMedia, key=lambda song: (song['artist']),     reverse=True)
        return  sortedByArtistList

    def displayUrl(self,newSong):
    #can't figure out the next step
    return ""

    def playSong(self, url):
        webbrowser.open_new_tab(url)
        return ""

主文件是:

search = raw_input("Find this Song: ")
results= m.searchSong(search)
pprint(results)


sortedResultByTitle = m.sortByTitle(results)

print "Sorted by Title"
pprint(sortedResultByTitle)

Tags: selfcomjsonhttpreturntitleartistyoutube
1条回答
网友
1楼 · 发布于 2024-03-29 02:32:45

那可能是你的主要档案

from pprint import pprint
import webbrowser
search = raw_input("Find this Song: ")
results= m.searchSong(search)
pprint(results)


sortedResultByTitle = m.sortByTitle(results)

print "Sorted by Title"

# expression: enumerate(sortedResultByTitle)
# explanation: this generates some kind of iterator, that puts the index of the every list-entry in front of it
# example: (0, first), (1, second), ... 
# 
# expression: list(enumerate(…))
# explanation: we know that enumerate returns some kind of iterator. for printing the contents, we have to build a sequence like a list.
# example: [ (0, first), (1, second), (2, third), ... ]
pprint(list(enumerate(sortedResultByTitle)))


"""
The following while-loop will continue looping until the break-statement is hit
and that will happen, if there is no error occurring within the try-clause
"""
while True:
    try:
        # throws an error, if input can not be converted to integer
        song_number = int(raw_input("Choose song by number: "))
        # throws an error, if song_number is not within those boundaries
        assert 0 <= song_number < len(sortedResultByTitle)
    except:
        print "Error"
    else:
        break

webbrowser.open_new_tab(sortedResultByTitle[song_number]['link'])

我忍不住修改了你的一个方法。输出较少,但我认为这是出于调试目的。你知道吗

class MusicLink(object):
    #...
    def searchSong(self,search):
        musicObject = self.loadData(dataFile)
        """
        The following code-line is a list-comprehension. (http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
        try to read it like a sentence
        Create a list of song(s) by taking every song in musicObject["LinkCollection"]
        but only if the lowercase search-string is within the song 's lowercase title 
        """
        return [song for song in musicObject["LinkCollection"] if search.lower() in song["title"].lower() ]
    #…

在主要的编辑之后,我添加了整个类的实现

你不知道如何设计一个类,尤其是方法。这就是我对整件事的看法。你知道吗

import webbrowser
import json
from pprint import pprint
from operator import itemgetter
class MusicLink():
    """
    This class stores a list of songs.
    """
    #
    def __init__(self, lst = None):
        print "Karaoke"
        # you did not use any instance-variables in your class although this is the whole sense of writing a class:
        # store data in a structured way and use methods to deal with those data
        # that's the way to store an instance variable: self.instance_variable = value
        self._songlist = lst or []
        """
        a = lst or [] 
        # same like means
        if lst is None: # short and more general: if not lst:
            a = []
        else:
            a = lst 
        """
        #
    def loadData(self,dataFile):
        # you watched the video, so have heard about with... advantage: you don't have to close the file
        with open(dataFile) as json_data:
            # the json-data are stored in the class variable
            self._songlist = json.load(json_data)["LinkCollection"]
        #
    def searchSong(self,search):
        """
        The following code-line is a list-comprehension. (http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
        try to read it like a sentence
        Create a list of song(s) by taking every song in musicObject["LinkCollection"]
        but only if the lowercase search-string is within the song 's lowercase title 
        """
        return MusicLink([song for song in self._songlist if search.lower() in song["title"].lower() ])
        # instead of returning a list, I return a MusicLink-Object, so I can use all the other method on it
        #
    def sortByTitle(self):
        # instead of deliver the foundMedia it sorts the data in the instance-variable
        return MusicLink(sorted(self._songlist, key=itemgetter('title')))
        # sorted returns a list and that is what MusicLink needs to create a new, sorted instance
        #
    def sortByArtist(self):
        #pprint(foundMedia)
        # ^- I uncommented this line, because it is not good, if two similar functions like sortByTitle and sortByArtist differ in printing behaviour
        sortedByArtistList = sorted(self._songlist, key=itemgetter('artist'), reverse=True)
        return  MusicLink(sortedByArtistList)
        #
    def chooseSong(self):
        print "CHOOSE SONG BY NUMBER"
        pprint(dict(enumerate(self._songlist)))
        #
        while True:
            try:
                entered = int(raw_input('Enter your song number (not id):'))
                chosen_song = self._songlist[entered]
            except:
                # this happens, if var entered isnot int or if it is out of range of songlist
                print " -> Not found!"
            else:
                print " -> Play song..."
                break
        webbrowser.open_new_tab(chosen_song['link'])

这就是如何使用它:

ml = MusicLink()
Karaoke

ml.loadData('jsontest.json')

ml.chooseSong()
CHOOSE SONG BY NUMBER
{0: {u'artist': u'Whitney Houston',
     u'id': 1,
     u'link': u'http://www.youtube.com/watch?v=3JWTaaS7LdU',
     u'title': u'I Will Always Love You'},
 1: {u'artist': u'Roberta Flack',
     u'id': 2,
     u'link': u'http://www.youtube.com/watch?v=LQ2t5e7stVM',
     u'title': u'Killing Me Softly'},
 2: {u'artist': u'Mariah Carey',
     u'id': 3,
     u'link': u'http://www.youtube.com/watch?v=0IA3ZvCkRkQ',
     u'title': u'Hero'},
 3: {u'artist': u'Christina Aguliera',
     u'id': 4,
     u'link': u'http://www.youtube.com/watch?v=wwCykGDEp7M',
     u'title': u'Hurt'},
 4: {u'artist': u'Etta James',
     u'id': 5,
     u'link': u'http://www.youtube.com/watch?v=S-cbOl96RFM',
     u'title': u'At Last'}}

Enter your song number (not id):3
 -> Play song...

ml.searchSong("you").chooseSong()
Karaoke
CHOOSE SONG BY NUMBER
{0: {u'artist': u'Whitney Houston',
     u'id': 1,
     u'link': u'http://www.youtube.com/watch?v=3JWTaaS7LdU',
     u'title': u'I Will Always Love You'}}

Enter your song number (not id):2
 -> Not found!

Enter your song number (not id):2
 -> Not found!

Enter your song number (not id):0
 -> Play song...

相关问题 更多 >