如何在Python中用Regex查找和替换URI片段?

问题描述 投票:0回答:1

你好!

我正在尝试在文本文件中查找和替换URI片段,但我不知道该怎么做。

[某些资源以URL开头(例如http://www.example.com/{fragment}),其他资源以定义的前缀开头(例如example:{fragment})。两个片段都代表同一个对象,因此必须对所有出现的前缀和URL片段进行任何更改,反之亦然。

这里是一个例子:

每次出现http://www.example.com/Example_1example:Example_1时,我都想用UUID(例如Example_1)替换文件中所有出现的片段186e4707_afc8_4d0d_8c56_26e595eba8f0,导致所有出现都被http://www.example.com/186e4707_afc8_4d0d_8c56_26e595eba8f0替换]或example:186e4707_afc8_4d0d_8c56_26e595eba8f0

对于文件中的每个唯一片段,都需要进行此操作,这意味着Example_2Example_3等将使用不同的UUID。

到目前为止,我已经设法找到此正则表达式行:(((?<=### http:\/\/archive\.semantyk\.com\/).*)|(?<=archive:)([^\s]+))可用于识别片段,但我确实对替换部分感到困惑。

我相信这不是一个难题,但我确实知道这很复杂。

我希望我对自己的解释足够好,但是如果我不满意,请告诉我。

您知道如何解决吗?

非常感谢您阅读本文。


编辑:

我尝试通过此输入使用re.sub:

###  http://archive.semantyk.com/Abbreviation
archive:Abbreviation rdf:type owl:Class ;
                     rdfs:subClassOf archive:Word .


###  http://archive.semantyk.com/Ability
archive:Ability rdf:type owl:Class ;
                rdfs:subClassOf archive:Quality .

并产生此结果:

###  http://archive.semantyk.com/4f5b99bb_2bff_4166_8468_0134a1d864ae
archive:4f5b99bb_2bff_4166_8468_0134a1d864ae rdf:type owl:Class ;
                     rdfs:subClassOf archive:4f5b99bb_2bff_4166_8468_0134a1d864ae .


###  http://archive.semantyk.com/4f5b99bb_2bff_4166_8468_0134a1d864ae
archive:4f5b99bb_2bff_4166_8468_0134a1d864ae rdf:type owl:Class ;
                rdfs:subClassOf archive:4f5b99bb_2bff_4166_8468_0134a1d864ae .

但是这是不正确的,因为UUID相同,但是资源(片段)不同。

python regex text refactoring uri
1个回答
0
投票

您可以使用re(regex)模块来替换匹配的模式,让我们来看:

import re
re.sub(pattern, repl, string, count=0, flags=0)

0
投票

我尝试通过此输入使用re.sub:

###  http://archive.semantyk.com/Abbreviation
archive:Abbreviation rdf:type owl:Class ;
                     rdfs:subClassOf archive:Word .


###  http://archive.semantyk.com/Ability
archive:Ability rdf:type owl:Class ;
                rdfs:subClassOf archive:Quality .

并产生此结果:

###  http://archive.semantyk.com/4f5b99bb_2bff_4166_8468_0134a1d864ae
archive:4f5b99bb_2bff_4166_8468_0134a1d864ae rdf:type owl:Class ;
                     rdfs:subClassOf archive:4f5b99bb_2bff_4166_8468_0134a1d864ae .


###  http://archive.semantyk.com/4f5b99bb_2bff_4166_8468_0134a1d864ae
archive:4f5b99bb_2bff_4166_8468_0134a1d864ae rdf:type owl:Class ;
                rdfs:subClassOf archive:4f5b99bb_2bff_4166_8468_0134a1d864ae .

但是这是不正确的,因为UUID相同,但是资源(片段)不同。

© www.soinside.com 2019 - 2024. All rights reserved.