【问题标题】:Python: import URLs into listPython:将 URL 导入列表
【发布时间】:2011-11-27 14:06:45
【问题描述】:

我正在尝试制作一个 python 脚本,可以从 subscene.com 下载 How I Met Your Mother 的字幕。 我是 Python 和编程新手。

我希望将搜索结果放在一个列表中,然后打印出来,以便用户选择正确的 URL。问题是我不知道如何从搜索结果中创建一个列表。有人知道怎么做吗?

这是我目前所做的:

import urllib

class Subtitle_downloader(object):

    def __init__(self):
        self.SearchCriteria = ['How.I.Met.Your.Mother']
        self.Episode = str(raw_input('Enter episode: '))
        self.Carateristics = str(raw_input('Enter caracteristics: ')) #'HDTV' for an example
        self.SearchCriteria.append('S07E'+self.Episode)
        self.SearchCriteria.append(self.Carateristics)
        print self.SearchCriteria

    def SubDL(self, SubUrl):
        self.AllSubs = urllib.urlopen(SubUrl).readlines()
        for item in self.AllSubs:
            if self.SearchCriteria[0] and self.SearchCriteria[1] in item:
            #Create a list

t=Subtitle_downloader()
t.SubDL('http://subscene.com/How-I-Met-Your-Mother-Seventh-Season/subtitles-90698.aspx')

【问题讨论】:

  • 检查逻辑...如果 self.SearchCriteria[0] 和 self.SearchCriteria[1] 在项目中,您真的想要吗?这将检查 SearchCriteria[0] 是否为 True,而不是是否在 item 中。

标签: python list url


【解决方案1】:

如果您不想使用列表推导(可能看起来有点复杂),您也可以简单地创建一个空列表,并将项目附加到其中:

def SubDL(self, SubUrl):
    subList = []
    self.AllSubs = urllib.urlopen(SubUrl).readlines()
    for item in self.AllSubs:
        if self.SearchCriteria[0] and self.SearchCriteria[1] in item:
           subList.append(item)
    return subList

【讨论】:

  • 谢谢这两个答案都非常有帮助。但我面临一个新问题:是否可以让 python 以与子场景中显示的方式相同的方式打印超链接?
  • 查看我的回复的编辑。使用字符串格式设置您想要的格式。
【解决方案2】:

您可以使用列表推导:

def SubDL(self, SubUrl):

    l = [item for item in urllib.urlopen(SubUrl).readlines()
         if self.SearchCriteria[0] in item and self.SearchCriteria[1] in item]
    for item in l:
        print('An item: {}'.format(item))

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 2012-12-31
    • 2017-08-04
    • 2017-12-15
    • 2015-07-06
    • 2022-11-22
    • 2014-08-31
    相关资源
    最近更新 更多