如何替换文本块中的多个正则表达式匹配 - python

我正在尝试将段落中的多个匹配项转换为链接,同时在最终输出中保留周围的文本。我匹配的模式让人想起Markdown的超链接语法,这是一种允许非技术用户定义他们想要在输入中链接哪些文本的方式(我正在通过Sheets API / Python访问的Google Sheet)。我捕获的第一个组是链接的文本,第二个是查询字符串中键的值。

我已经能够成功匹配此模式的单个实例,但是我的替换字符串替换了输出中的整个段落。

text = "2018 was a big year for my sourdough starter and me. Mostly 
we worked on developing this [tangy bread](19928) and these [chewy 
rolls] (9843). But we were also just content keeping each other 
company and inspired to bake."

def link_inline(text):
    # expand a proper link around recipe id
    ref = re.search(r"(\[.*?\]\(\d+\))", text, re.MULTILINE).group(1)
    if (len(ref) > 0):
        link = re.sub("\[(.*?)\]\((\d+)\)", r"<a href='https://www.foo.com/recipes?rid=\2'>\1</a>", ref)
        return text
    else:
        return "replacement failed"

目的是使此输出保持段落的完整性,并简单地将\[(.*?)\]\((\d+)\)模式匹配替换为以下字符串,包括对组的反向引用:<a href="https://www.foo.com?bar=\2">\1</a>

因此,它将需要循环遍历文本以替换所有匹配项(大概用re.finditer?),并且还要在模式匹配项之外保留原始文本。但是我不确定如何正确定义循环并执行此替换操作而不会仅用替换字符串覆盖整个段落。

参考方案

我使用了re.compile,而不是在整个组中加上括号,而是在.*?上放置了一对,在\d+上放置了另一对,因为这两部分代表了我们想要提取并放入URL中的文本。

import re

def link_inline(text):
    # expand a proper link around recipe id
    ref = re.compile("\[(.*?)\]\((\d+)\)")
    replacer = r'<a href="https://www.foo.com/recipes?rid=\2">\1</a>'
    return ref.sub(replacer, text)


text = """
2018 was a big year for my sourdough starter and me. Mostly we worked on
 developing this [tangy bread](19928) and
 these [chewy rolls](9843). But we were also just
 content keeping each other company and inspired to bake.
"""

print(link_inline(text))

输出:

2018 was a big year for my sourdough starter and me. Mostly we worked on
 developing this <a href="https://www.foo.com/recipes?rid=19928">tangy bread</a> and
 these <a href="https://www.foo.com/recipes?rid=9843">chewy rolls</a>. But we were also just
 content keeping each other company and inspired to bake.

为了进行健全性检查,我尝试在括号中加上一些不是链接的括号和方括号,例如字符串(this) here中的[this] heretext。一切仍然顺利。

Python Pandas导出数据 - python

我正在使用python pandas处理一些数据。我已使用以下代码将数据导出到excel文件。writer = pd.ExcelWriter('Data.xlsx'); wrong_data.to_excel(writer,"Names which are wrong", index = False); writer.…

Python-crontab模块 - python

我正在尝试在Linux OS(CentOS 7)上使用Python-crontab模块我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python:在不更改段落顺序的情况下在文件的每个段落中反向单词? - python

我想通过反转text_in.txt文件中的单词来生成text_out.txt文件,如下所示:text_in.txt具有两段,如下所示:Hello world, I am Here. I am eighteen years old. text_out.txt应该是这样的:Here. am I world, Hello old. years eighteen a…