转换URL,Python

0 投票
1 回答
781 浏览
提问于 2025-04-16 06:41

我有一个文本文件,里面包含了一些网址:

[http://igu.org.ru/ International Geographical Union - Russian National Committee]
[http://www.geografos.org Colegio de Geógrafos - España]
[http://www.geografs.org Col.legi de Geògrafs - Catalunya]
[http://www.geografs.org]

现在我想按照以下方式处理这些外部链接(顺序是固定的):

把"[url 任何文字]"替换成"任何文字",其中"url"是一个网址(比如,以"http://"开头)。

把"[url]"替换成"url"

import re
def openfile(filename):
    with codecs.open(filename, encoding="utf-8") as F:
        replace = F.read()
        replace = re.sub(r'\[http://.+ ...) # should replace "[url any text]" with "any text"
        replace = re.sub(...) # should replace "[url]" with "url"

有什么建议吗?

1 个回答

2
re1 = re.compile(r'\[(http[^\s]*)\s(.*)\]')
re2 = re.compile(r'\[(http[^\s]*)\]')
with codecs.open(filename, encoding='utf-8') as F:
    text = F.read()
    pre_filter = re1.sub('\g<2>', text)
    result = re2.sub('\g<1>', pre_filter)

来处理你的文本。 如果想了解更多背景信息,可以阅读: http://docs.python.org/howto/regex.html#search-and-replace

撰写回答