【问题标题】:python 3 url concatenate from file and listpython 3 url从文件和列表连接
【发布时间】:2020-01-16 08:20:18
【问题描述】:

我有一个包含多个 url 的文件并列出了 url 路径。我正在尝试将它们与列表中的 url 路径连接或连接在一起。我在尝试让它工作时遇到了很多麻烦。

文件有这样的网址

foobar.com
foobar.com.tk
foobar.org
list1 = ['/foobar.php','/foobar.html','/foobar.php']

with open('file1.txt') as f:
    Nlist = [line.strip() for line in f]

我不知道这是否重要,但是带有 url 的文件没有 http:// 标头,当我尝试使用路径加入列表中的 url 时,我不断收到错误或代码都聚集在一起...如何将文件中的 url 与列表中的路径连接起来?

【问题讨论】:

  • 你能分享你期望得到的这个样本数据的输出吗?这将有助于使问题更清晰
  • 请提供有关错误和任何实际/预期输出的更多详细信息。无论数据来自何处,您都可以使用 list_a + list_b 连接列表。
  • 哦,是的,我很抱歉我本来打算这样做,但忘记了输出应该是这样的``` foobar.com/foobar.php foobar.org/foobar.html foobar.com.tk/foobar.php 或 foobar.com/foobar.php foobar .org/foobar.html foobar.com.tk/foobar.php ```
  • 所以我必须先将文件放入列表中吗?我正在尝试遍历它们,以便我可以使用每个单独的 url 发出发布请求...如果我这样做 list_a + list_b 它只是将列表添加在一起我需要能够将文件中的 url 与路径中的路径连接起来列出,这样他们就形成了一个 url foobar.com/foobar.php 这样......
  • lines = list(open(filename, 'r'))

标签: python python-3.x list concatenation


【解决方案1】:

您可以使用itertools.product 获得每个网址组合:

from itertools import product
from pprint import pprint

list1 = ["/foobar.php", "/foobar.html", "/foobar.php"]

with open("file1.txt") as f:
    pprint(
        set(
            "https://%s%s" % (root, path)
            for root, path in product(map(str.strip, f), list1)
        )
    )

网址:

{'https://foobar.com.tk/foobar.html',
 'https://foobar.com.tk/foobar.php',
 'https://foobar.com/foobar.html',
 'https://foobar.com/foobar.php',
 'https://foobar.org/foobar.html',
 'https://foobar.org/foobar.php'}

注意:您可以在此处使用set() 从结果中删除重复的网址。

【讨论】:

    【解决方案2】:
    list1 = ['/foobar.php','/foobar.html','/foobar.php']
    
    with open('file1.txt') as f:
        Nlist = [line.strip() for line in f]
    
    for i in range(len(Nlist)):
        pth = 'https://' + Nlist[i] + list1[i]
        print(pth)
    

    os.path.join() 似乎并不喜欢所有的点,所以看来你必须求助于自己的连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多