gpt4 book ai didi

python - 如何使用re.sub基于模式字典替换文本的某些部分并替换python中的值?

转载 作者:行者123 更新时间:2023-12-04 10:12:25 24 4
gpt4 key购买 nike

我有一个要用于文本替换的前缀列表。每当我用相应的值替换整个匹配的文本时,我的程序都会工作,但如果我想保留匹配文本的某些部分并使用分组替换其他部分,我的程序就不会工作:

prefixes = {
r"http://www.w3.org/2002/07/owl#([a-z]+)": r"owl:\1",
r"http://www.w3.org/1999/02/22-rdf-syntax-ns#([a-z]+)": r"rdf:\1",
r"http://www.w3.org/2000/01/rdf-schema#([a-z]+)": r"rdfs:\1",
r"http://schema.org/": "schema",
r"http://www.w3.org/2001/XMLSchema#([a-z]+)": r"xsd:\1",
r"http://purl.org/linked-data/sdmx#([a-z]+)": r"sdmx:\1",
r"http://www.w3.org/XML/1998/namespace": r"xml"
}
# test = "http://www.w3.org/XML/1998/namespace" # works for this
test = "http://www.w3.org/2000/01/rdf-schema#a" # Does not work!

regex = re.compile("|".join(map(re.escape, prefixes.keys())))

test = regex.sub(lambda match:prefixes[match.group(0)], test)

我想用“rdfs:a”替换测试,但它不能这样工作。我应该如何更改代码以在这种情况下工作?

最佳答案

有点框架挑战,但“为什么要打扰团体”?无论如何,您的正则表达式都不匹配行尾( $ ),因此您在这里唯一丢失的是确保 # 之后的所有内容。以单个 a-z 开头特点:

import re

prefixes = {
r"http://www.w3.org/2002/07/owl#": r"owl:",
r"http://www.w3.org/1999/02/22-rdf-syntax-ns#": r"rdf:",
r"http://www.w3.org/2000/01/rdf-schema#": r"rdfs:",
r"http://schema.org/": "schema",
r"http://www.w3.org/2001/XMLSchema#": r"xsd:",
r"http://purl.org/linked-data/sdmx#": r"sdmx:",
r"http://www.w3.org/XML/1998/namespace": r"xml"
}
regex = re.compile("|".join(map(re.escape, prefixes.keys())))


test1 = "http://www.w3.org/XML/1998/namespace"
test2 = "http://www.w3.org/2000/01/rdf-schema#a"

assert regex.sub(lambda match:prefixes[match.group(0)], test1) == "xml"
assert regex.sub(lambda match:prefixes[match.group(0)], test2) == "rdfs:a"

关于python - 如何使用re.sub基于模式字典替换文本的某些部分并替换python中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com