Benutzer:FalkBot/FindMisspellings.py

aus Wiki Aventurica, dem DSA-Fanprojekt
Dieses Skript benötigt als Pywikipediabot-Version mindestens den snapshot 2007-06-19.

Autor(en)[Bearbeiten | Quelltext bearbeiten]

Beschreibung[Bearbeiten | Quelltext bearbeiten]

Funktion[Bearbeiten | Quelltext bearbeiten]

Sucht nach Tippfehlern und meldet sie hier.

Um neue Tippfehler zu definieren, bitte vorher die Anleitung lesen.

Aufruf[Bearbeiten | Quelltext bearbeiten]

FindMisspellings.py -<typ>:<quelle>   { -<typ>:<quelle> }
  • Wird das Skript falsch oder mit dem Paramter -help aufgerufen, wird eine Aufruferklärung ausgegben.

Beispiele[Bearbeiten | Quelltext bearbeiten]

Zeige mir die komplette Aufrufhilfe an:

FindMisspellings.py -help

Durchsucht alle Artikel im Wiki beginnend bei Anfang:

FindMisspellings.py -start:Anfang
#Die allererste Seite im Wiki ist "!"

Durchsucht alle neuen Artikel im Wiki:

FindMisspellings.py -new

Status[Bearbeiten | Quelltext bearbeiten]

  • Beta-Version (keine bekannten, unbehobenen Probleme)

Bekannte Probleme[Bearbeiten | Quelltext bearbeiten]

  • Bis jetzt meldet das Skript nur das jeweils erste auftreten eines bestimmten Fehlers. --Falk Steinhauer 22:04, 31. Jul. 2007 (CEST)

Quellcode[Bearbeiten | Quelltext bearbeiten]

# -*- coding: utf-8  -*-
"""
This script searches all articles in the given source for misspellings.

See the global variables for the page that defines the common misspellings, ...
and the page, where they should be reported.


Defining the list of articles to process:
                        
&params;
"""
#
# This file is freeware
#

import wikipedia
import pagegenerators 
import re

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;':     pagegenerators.parameterHelp,
}

# global variables:
sListOfMisspellings = 'Wiki Aventurica:Liste von Tippfehlern'
sListOfDetectedPages = 'Wiki Aventurica:Liste von Tippfehlern/Artikel mit Tippfehlern'

WrongStrings = []    # the list of all misspelled strings that should be searched
RightStrings = []    # the list of all correct replacements for the wrong strings

###############################################################################################

def main():
    GetWrongStrings()
#    DebugHelp()
    
    # read commandline argument:
    for ActArg in wikipedia.handleArgs():    # this will extract options, that are appropriate for the wikipedia module
        gen = pagegenerators.GeneratorFactory().handleArg(ActArg)
        if gen != None:
            gen = pagegenerators.PreloadingGenerator(gen)
            for Article in gen:
                FindMisspellings(Article)
        else:
           wikipedia.showHelp('FindMisspellings')

###############################################################################################

def GetWrongStrings():
    """Parse the page that defines the misspellings!"""
    global sListOfMisspellings
    global WrongStrings
    global RightStrings
    
    sSourceCode = wikipedia.Page(wikipedia.getSite(), sListOfMisspellings).get()
    RegExp = re.compile('\*([^\(]+) \((.+)\)', re.LOCALE | re.UNICODE)
    Lines = sSourceCode.split('\n')
    for sLine in Lines:
        WrongStrings.append( RegExp.sub('\\1', sLine) )
        RightStrings.append( RegExp.sub('\\2', sLine) )

###############################################################################################

def DebugHelp():
    """
    You might use this function for debugging purposses.
    It prints the parsing results of GetWrongStrings() to a file named test.txt.
    
    Those strings that can't be printed because of encoding-/decoding-problems are printed to stdout.
    """
    file = open('test.txt', 'w')
    for i in range(0,len(WrongStrings)):
        try:
            print >>file, WrongStrings[i], RightStrings[i]
        except UnicodeEncodeError:
            print WrongStrings[i], RightStrings[i]
            
###############################################################################################
        
def FindMisspellings(Article):
    try:
        sSourceCode = Article.get()
    except wikipedia.IsRedirectPage:
        return    # skip an continue with next
    except wikipedia.NoPage:
        return    # skip an continue with next
    
    for i in range(0,len(WrongStrings)):
        RegExp = re.compile('(?<!\w)' + WrongStrings[i] + '(?!\w)', re.LOCALE | re.UNICODE)
        ErrorMatch = RegExp.search(sSourceCode)    # NOTE: This will just match the 1st appearance of the misspelled string!!!
        if ErrorMatch != None:
            AddEntry(Article, ErrorMatch.start(), ErrorMatch.end())

###############################################################################################

def AddEntry(Article, iErrorStartPos, iErrorEndPos):
    """
    This function will add an entry to the list of found misspellings.
    The implementation may vary.
    
    1st arg:    the wikipedia.Page-object of the article containing the error
    2nd arg:    the index of the 1st appearance of the error
    3rd arg:    the index of the 1st character, that is not part of the error
    """
    global sListOfDetectedPages
    
    # build entry:
    sErrorPreFix = '</nowiki><font color=red>'
    sErrorPostFix = '</font>'
    iNumExtraChars = 20        # the number of characters in an entry that should precede or follow the error string
    
    sMisspelledCode = Article.get()
    
    iStartPos = iErrorStartPos - iNumExtraChars
    if iStartPos < 0:
        iStartPos = 0

    iEndPos = iErrorEndPos + iNumExtraChars
    if iEndPos >= len(sMisspelledCode):
        iEndPos = len(sMisspelledCode)

    sErrorMark = sErrorPreFix + sMisspelledCode[iErrorStartPos:iErrorEndPos] + sErrorPostFix
    sEntry = '\n*[[' + Article.title() + "]] - <nowiki>" + sMisspelledCode[iStartPos:iErrorStartPos] + sErrorMark + sMisspelledCode[iErrorEndPos:iEndPos] + ""

#    try:
#        print sEntry
#    except UnicodeEncodeError:
#        pass
            
    # add entry:
    sSummaryStart = '[[Benutzer:FalkBot/FindMisspellings.py|FindMisspellings.py]]: [[Wiki Aventurica:Liste von Tippfehlern/Artikel mit Tippfehlern|Tippfehler]] in [['
    wikipedia.setAction(sSummaryStart + Article.title() + ']] gefunden')
    DetectionArticle = wikipedia.Page(wikipedia.getSite(), sListOfDetectedPages)
    DetectionArticle.put(DetectionArticle.get() + sEntry)    # return the old source code with the new entry added
    
###############################################################################################

if __name__ == "__main__":
    try:
        main()
    finally:
        wikipedia.stopme()