我正在编写一个小脚本,用于使用pywikibot自动更正维基百科之间的翻译链接。我正在寻找现有的链接,并希望以包含所有页面链接的标准格式来重写它们。
我正在寻找的文字看起来有点像
{{Trad|EN=Under Spring|FR=Sources Interdites|DE=Verbotene Quellen}}
或多行类似
{{Trad |DE=Urwurzeln |EN=Prime Roots |ES=Raíces Primarias |FR=Primes Racines |RU =Изначальных Корней |H = |palette=primes }}
我设法通过
在Wiki页面源中找到这两个实例。reg_strg = '{{trad([\w\s\|\=]*)}}'
rex = re.search(reg_strg, text, re.IGNORECASE | re.MULTILINE)
这让我想到了模板的核心(对于第一种情况)
|EN=Under Spring|FR=Sources Interdites|DE=Verbotene Quellen
,与第二行的多行字符串类似。
但是,我现在在replace命令中使用相同的reg_strg,它无法进行任何替换,文本保持不变,从读取的内容创建new_strg来构成替换字符串。但是结果与new_strg是多行字符串还是简单的“ flobberigoo”无关。
text = re.sub(reg_strg, new_strg, text, re.IGNORECASE | re.MULTILINE)
因此,显然re.search和re.sub之间存在一些差异-但是我在文档中找不到这一点(即使我知道re.search和re.match之间的差异,我也是如此理解,该re.sub的行为应与第一个类似。)
我想念什么?如何用字符串替换在页面中找到的上述正则表达式?
出于完整性考虑,这是包括调试打印在内的完整功能:
def replace_translation_template(self, text, translations):
"""
@param text The page text to look through
@param translations dictionary of translations
"""
reg_strg = '{{trad([\w\s\|\=]*)}}'
rex = re.search(reg_strg, text, re.IGNORECASE | re.MULTILINE)
print("Replacing:")
try:
print(rex.group(1))
strgs = rex.group(1).split('|')
print(strgs)
new_strg = ""
for lang,pagename in translations.items():
if pagename is None:
pagename = ""
new_strg += '|' + lang.upper() + '=' + pagename + '\n'
#print("New_strg: ", new_strg)
for lang in translations.keys():
for (n,str) in enumerate(strgs):
if lang.upper() in str:
strgs.pop(n)
for s in strgs:
if len(s) > 2:
new_strg += '|' + s + '\n'
print(new_strg, '\n')
print('\n with \n \n')
text = re.sub(reg_strg, new_strg, text, re.IGNORECASE | re.MULTILINE)
print(text)
except:
print("no text matched:", rex)