首页 > 解决方案 > 如何将http附加到每个url的文本文件

问题描述

我有大量没有 http 标头的 URL。我正在尝试完成两件事:

  1. 读取没有 HTTP 头 exp (www.google.com) 的 URL 的文本文件,并将它们拆分为 1000 个块文本文件。

  2. 将“http://”附加到每个链接 exp ( http://www.google.com )

目前我只能完成第一步。

from itertools import zip_longest

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(fillvalue= fillvalue, *args)

n = 1000

with open('sites.txt') as f:
    for i, g in enumerate(grouper(n, f, fillvalue=''), 1):
        with open('s_{0}'.format(i), 'w') as fout:
            fout.writelines(g)

标签: python

解决方案


将“http://”附加到每个链接 exp ( http://www.google.com )

如果您有一个 URL 列表并且想要添加https://到每个项目,您可以使用列表理解和字符串格式。

urls = ['https://{}'.format(url) for url in urls]

如果文件中有这些,请在换行符上拆分文件以创建列表:

with open('sites.txt') as f:
    urls = ['https://{}'.format(url) for url in f.splitlines()]

** 注意:您的问题与 HTTP 标头无关


推荐阅读