我有一个txt文件,其中包含一些网址:
[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 any text]
”替换为“any text
”,其中“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"
有什么建议吗?
答案 0 :(得分: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