사용자:Utoleetest/replace.py 예제

< 사용자:Utoleetest
Utoleetest (토론 | 기여)님의 2020년 5월 15일 (금) 00:27 판 (유용한 Pywikibot 코드 설명)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

Pywikibot의 Replace.py 활용예제를 올립니다.

더 좋은 예제들 : Wikipedia:hu:Szerkesztő:Bináris/Fixes_and_functions_HOWTO

틀의 텍스트 한번에 바꾸는 패턴

예시 : {{대한민국 시군구 정보}} 틀을 {{마을 정보}} 틀로 교체할 때 유용한 스크립트.

def replace_local(match): #틀 치환
    import re
    text=match.string
    text=text.replace(u'{{기초자치단체 정보', u'{{마을 정보')
    text=text.replace(u'{{기초자치단체', u'{{마을 정보')
    text=text.replace(u'{{대한민국 시군구 정보', u'{{마을 정보')
    text=text.replace(u'{{대한민국 시군구', u'{{마을 정보')
    text=text.replace(u'|총인구', u'|인구')
    text=text.replace(u'|총인구_조사년도', u'|인구 조사년도')
    text=re.sub('\|대표이미지(\s|\t)*=(\s)*(.*?\.(JPG|jpg|PNG|png))', r'|그림1=[[파일:\3|300px]]', text)
    text=text.replace(u'|그림설명', u'|그림1설명')
    text=re.sub('\|행정동(\s|\t)*=(\s)*(.*?)(\|)?', r'|하위 행정구역1 명칭=행정동\n|하위 행정구역1=\3\4', text)
    text=re.sub('\|법정동(\s|\t)*=(\s)*(.*)(\|)?', r'|하위 행정구역2 명칭=법정동\n|하위 행정구역2=\3\4', text)
    text=re.sub('\|읍(\s|\t)*=(\s)*(.*)(\|)?', r'|하위 행정구역3 명칭=읍\n|하위 행정구역3=\3\4', text)
    text=re.sub('\|면(\s|\t)*=(\s)*(.*)(\|)?', r'|하위 행정구역4 명칭=면\n|하위 행정구역4=\3\4', text)
    text=re.sub('\|(구청장|시장|군수)(\s|\t)*=(\s)*(.*)(\|)?', r'|지도자 직함=\1\n|지도자=\4\5', text)
    text=re.sub('\|국회의원(\s|\t)*=(\s)*(.*)(\|)?', r'|지도자2 직함=국회의원\n|지도자2=\3\4', text)
    text=re.sub('\|(구|시|군)청소재지(\s|\t)*=(\s)*(.*)(\|)?', r'|관청명={{PAGENAME}}청\n|관청소재지=\4\5', text)
    text=re.sub('\|(구|시|군)목(\s|\t)*=(\s)*(.*)(\|)?', r'|상징1 종류=\1목\n|상징1=\4\5', text)
    text=re.sub('\|(구|시|군)화(\s|\t)*=(\s)*(.*)(\|)?', r'|상징2 종류=\1화\n|상징2=\4\5', text)
    text=re.sub('\|(구|시|군)조(\s|\t)*=(\s)*(.*)(\|)?', r'|상징3 종류=\1조\n|상징3=\4\5', text)
    return text


fixes['template_local_infobox']={ #dotall을 사용할 것.
    'regex':True,
    'msg':{
        'ko': u'봇:시군구 정보 틀 내용을 마을 정보로 대체',
    },
    'replacements': [
        (r'^(.|\n)*\{\{대한민국 시군구( 정보)?(\s|\n)*\|((.|\n)*?)\}\}(.|\n)*$', replace_local),
        (r'^(.|\n)*\{\{기초자치단체( 정보)?(\s|\n)*\|((.|\n)*?)\}\}(.|\n)*$', replace_local),
    ]
    
}

문서 내부의 중복된 링크 제거

스크립트 소스 개선 시도중입니다. 일단 이 소스의 문제점은 틀 내부의 링크가 걸려있는 것을 무시하는 옵션이 없습니다.

def multilink_removal(match):
    pretext = match.string[:match.start()]
    if '[[' + match.group(1) + ']]' in pretext or '[[' + match.group(1) + '|' in pretext:
        #This text was already linked.
        if match.group(2): #Is there a piped part? Return it without the pipe.
            return match.group(2)[1:]
        else: #Return the text among brackets
            return match.group(1)
    else:
        # This is the first linked occurence of this text, leave untouched.
        return match.group()

fixes['multilink']= { #Function from https://hu.wikipedia.org/wiki/Szerkesztő:Bináris/Fixes_and_functions_HOWTO
 
    #This fix will remove multiple links of the same text in one article
    #TODO: Don't remove the link if the text has previously been linked only
    #      in an infobox at the beginning of the article, and this occurence
    #      is outside of that infobox.
    #TODO: exclude image description texts from pretext, handle nested brackets
    #      in image links
    'regex': True,
    'msg': {
           'en':u'Bot: unlinking multiple occurences with manual edit',
           'ko':u'봇:문서 내 중복으로 나타난 링크 제거',
    },
    'replacements': [
        (r'\[\[(.*?)(\|.*?)?\]\]', multilink_removal),
    ],
    'exceptions': {
        'inside-tags': [
            'hyperlink',
            'interwiki',
        ],
        'inside': [
            r'\[\[([Ff]ile|파일):.*?\]\]' #Images, works partially
        ],
     }
}