Python 我应该如何编写获得';链接';通过JSON搜索后得到的结果的值?

Python 我应该如何编写获得';链接';通过JSON搜索后得到的结果的值?,python,json,class,oop,Python,Json,Class,Oop,这里是Python初学者。 我试图找出如何编写一个方法,在搜索歌曲标题或对列表排序后获取“link”值,并将其播放。比如说,我会输入“伤害”这个词,它会告诉我它被找到了。我遇到的问题是试图获取它的链接并打开Youtube网站。Json文件的加载非常好。我只需要找出搜索后的下一步 Json文件是: {"LinkCollection": [{"title":"I Will Always Love You" , "artist":"Whitney Houston" , "link":"http:/

这里是Python初学者。 我试图找出如何编写一个方法,在搜索歌曲标题或对列表排序后获取“link”值,并将其播放。比如说,我会输入“伤害”这个词,它会告诉我它被找到了。我遇到的问题是试图获取它的链接并打开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}
]}
search = raw_input("Find this Song: ")
results= m.searchSong(search)
pprint(results)


sortedResultByTitle = m.sortByTitle(results)

print "Sorted by Title"
pprint(sortedResultByTitle)
课程为:

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 ""
主文件是:

{"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}
]}
search = raw_input("Find this Song: ")
results= m.searchSong(search)
pprint(results)


sortedResultByTitle = m.sortByTitle(results)

print "Sorted by Title"
pprint(sortedResultByTitle)

那可能是你的主要文件

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'])
主要编辑之后,我添加了整个类的实现 您不确定如何设计类,尤其是方法。这就是我对整件事的看法

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...

你能只发布价值观以及你想从中得到什么吗?你的代码不是问题所在-问题在于代码中没有的东西。那么你能把问题说清楚吗?例如,如果可能的话,删除代码?我希望我能说得更清楚。我添加了JSON代码,但我不会删除代码,以防有人需要查看。python风格的建议:您不必迭代歌曲列表的索引(
count
),特别是如果您没有将索引用于任何其他用途:
for song in musicObject[“LinkCollection”]:
。现在,您可以将每个
musicObject[“LinkCollection”][计数器]
替换为
song
谢谢您的代码,科芬。我很感激!代码正在运行。如果您还有时间,您介意解释一下您的代码吗?因为我想尽可能多地学习Python。@user2843235我在我的代码中添加了一些注释,以便于观看。我希望这是值得一看的,虽然你声称自己是一个Python初学者。@ USER 843355,因为你是新的堆栈溢出,我只是想指出:请考虑投票和/或检查我的答案视频非常翔实。我喜欢Python的强大功能,即使代码很简单。好的,我检查了你的答案。另外,您如何知道在创建类时放置哪些方法?这是让我最沮丧的部分。如果你的方法以某种方式使用对象
self
:如果一个方法提取并返回你的对象的信息(广义的“getter”)或修改你的对象,那么它似乎是正确的类设计。关于你们的具体课程,我将在回答中补充一些建议