在Python中,给定一个包含一些数据和URL的文本文件,只读取文本文件的URL的最简单方法是什么



在python中,我想读取这样一个文本文件中的url,但要超过1000行。我怎样才能只获取每一行的url?我需要将照片下载到我的数据集。感谢

===============

Lexi Ainsworth 11http://cdn.soaps.sheknows.com/images/news/22537_1_15562.jpg45,50174179 571435cb57e518ae0cc5855eb8f1bea0b89d447d8ad7f9379fbfb3ab794333f5Lexi Ainsworth 2 2http://trialx.com/curetalk/wp-content/blogs.dir/7/files/2011/10/celebrities/Lexi_Ainsworth-1.jpg130112396378

您确实遇到了一个难题,因为URL可以用括号括起来。你怎么知道右括号是URL的一部分还是不是URL的一部份?

这听起来像是正则表达式的工作,但不幸的是,它并不漂亮,也不完美。看见http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/关于为什么这个问题很难的一些例子和评论。

看看这个例子,可以找到一些有用的东西:

re.match('.*(https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[A-Za-z0-9+&@#/%=~_|])', 'abc http://www.google.fi def').groups(0)

根据空格拆分整个字符串,并选择所有以http/https开头的子字符串?我假设您在所有意图和目的上都受这两个协议的限制。

当您不知道该行是否以完整的超链接结束,或者该超链接是否在下一行继续时,就会出现问题。

好的,我明白了,无论如何,感谢你的帮助,我把代码放在这里,也许有人会帮忙。创建一个只包含url的txt

#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
# read the original text
 f=file("yourtextfile.txt", "r")
 content=f.read().splitlines()
 f.close()
# create the new file to save the url's
 f = file("newfile.txt","w")
 f = open("newfile.txt","w")
# for every line in the text
 for line in content:
    a = line
    contador = 0
    contador2 = 1
    for charac in a:
        # for every character in the line
        if charac == "t" :
            # if the next characters after t are http we copy the url till other t appear
            if a[contador2:contador2+4] == 'http':
                url = ""
                while a[contador2] != "t":
                    url = url + a[contador2]
                    contador2 = contador2+1
                f.write(url + 'n')
         contador = contador +1
         contador2 = contador2 +1
 f.close()

最新更新