ویکی‌پدیا:درخواست‌های ربات/کد پایه

کد زیر یک کد خام هست که تحت مجوز کریتیو کامنز ارایه می‌گردد. برای شروع کار با ربات و تقریبا حداقل‌های مورد نیاز برای ساخت یک ربات برای fa.wiki را دارا هست.

امکانات کد

ویرایش
  1. تابع تغییر عدد فارسی به انگلیسی یا با کمی تغییر انگلیسی به فارسی
  2. تابع حذف نیم‌فاصله‌های اشتباه
  3. مولد صفحه که در صورتی که متغییر arg=True باشد آرگونها فعال میگردند در غیر این صورت ربات فقط یک صفحه یا مجموعه‌ صفحه‌هایی را میگیرد.(همکنون arg=False)
  4. بخشی که شما عملی خاصی را از ربات انتظار دارید: در این بخش ربات نام صفحه و متن آن صفحه را به شما ارائه میدهد که با تغییر آنها بر اساس نیاز کدنویسی، میتوانید نتیجه بدست آمده را ذخیره نمایید.

ورودی ربات

ویرایش

ورودی ربات برای کار کردن در حالتی که arg=True باشد به شرح زیر است.

  1. آرگومان page-:نام یک صفحه یا مجموعه‌ صفحه‌هایی را از شما میگیرد مثال : -page:ایران یا -page:ایران,تهران,شیراز
  2. آرگومان cat-:نام یک رده یا مجموعه‌ رده‌هایی را از شما میگیرد مثال : -cat:هنرمندان ایران یا -page:هنرمندان ایران,هنرمندان تهران,هنرمندان شیراز
  3. آرگومان template-:نام یک الگو یا مجموعه‌ الگوهایی را از شما میگیرد مثال : -template:روی نقشه ایران یا -template:روی نقشه ایران,روی نقشه تهران,روی نقشه شیراز
  4. آرگومان start-:از یک حرف شروع به فعالیت میکند مثال:-start:ب ==> تمام صفحه‌هایی که بعد از حرف ب قرار دارند را برای ربات به ترتیب الفبا بارگذاری میکند.
    نکته:حروف ی، ک، پ، گ،ژ به علت مشکل در رتبه بندی الفبا فارسی در مدیاوبکی در انتهای الفبا قرار دارند.
    نکته:در صورتی که میخواهید صفحه‌ها در فضای نام دیگری جز فضای نام مقاله باشد مانند (رده، الگو، مدیاویکی،ویکی‌پدیا،راهنما،درگاه،پرونده،بحث و...) باید از کد ترکیبی استفاده کنید به عنوان مثال -start:الگو:ب یا -start:رده:ج ==> این ربات از رده‌هایی شروع به کار میکند که بعد از حرف ج باشند.
  • سایر آرگومانها را در اینجا مطالعه نمایید.
  • تذکر:برای وارد کردن عبارتهای فارسی که در فوق ذکر شد برای ویندوز باید از این ابزار استفاده نمایید.

کد پایه

ویرایش
#!/usr/bin/python
# -*- coding: utf-8 -*-
# BY: Z (User:ZxxZxxZ on fa.wikipedia)
# BY: رضا (User:reza1615 on fa.wikipedia)
# Distributed under the terms of the CC-BY-SA 3.0 .
"""
This bot will make direct text replacements. It  will retrieve information on
which pages might need changes either from an XML dump or a text file, or only
change a single page.
 
You can run the bot with the following commandline parameters:
 
-file        - Work on all pages given in a local text file.
               Will read any [[wiki link]] and use these articles.
               Argument can also be given as "-file:filename".
-cat         - Work on all pages which are in a specific category.
               Argument can also be given as "-cat:categoryname".
-template    - Work on all pages which are in a specific template.
               Argument can also be given as "-template:templatename".
-page        - Only edit a specific page.
               Argument can also be given as "-page:pagetitle". You can give this
               parameter multiple times to edit multiple pages.
-ref         - Work on all pages that link to a certain page.
               Argument can also be given as "-ref:referredpagetitle".
-filelinks   - Works on all pages that link to a certain image.
               Argument can also be given as "-filelinks:ImageName".
-links       - Work on all pages that are linked to from a certain page.
               Argument can also be given as "-links:linkingpagetitle".
-start       - Work on all pages in the wiki, starting at a given page. Choose
               "-start:!" to start at the beginning.
               NOTE: You are advised to use -xml instead of this option; this is
               meant for cases where there is no recent XML dump.
               i.e. "-start:Category:!" or "-start:template:a"
-except:XYZ  - Ignore pages which contain XYZ. If the -regex argument is given,
               XYZ will be regarded as a regular expression.
-summary:XYZ - Set the summary message text for the edit to XYZ, bypassing the
               predefined message texts with original and replacements inserted.
-template:XYZ- 
-namespace:n - Number of namespace to process. The parameter can be used
               multiple times. It works in combination with all other
               parameters, except for the -start parameter. If you e.g. want to
               iterate over all user pages starting at User:M, use
               -start:User:M.
-always      - Don't prompt you for each replacement
other:       - 
 
NOTE: Only use either -xml or -file or -cat or -template or-page, but don't mix them.
 
Examples:
        behsaz.py -start:!  برای تمام صفحات ویکی 
or
        behsaz.py -page:آرامگاه کورش
or      
        behsaz.py -cat:ایران
"""
__version__ = '$Id: $'

import wikipedia
import pagegenerators
import re, os, codecs, catlib
wikipedia.config.put_throttle = 0
wikipedia.put_throttle.setDelay()
faSite = wikipedia.getSite('fa')
enSite = wikipedia.getSite('en')
txtTmp=' '
faChrs = u'ءاآأإئؤبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیًٌٍَُِّْٓيك'
enChrs=u'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
faNums = u'۰۱۲۳۴۵۶۷۸۹'
arNums = u'٠١٢٣٤٥٦٧٨٩'
enNums = u'0123456789'

msg = u'ربات: ویرایشگر %s'

def BotRun(page,text_fa):
#--------------------------------------------------------------action that you want to do on pages-----------------
    print page
    print '+++++++++++++++++++++++++++++++++++++++++'
    print text_fa
    #return result_for_save







#----------------------------------------------------------end of action that you want to do on pages---------------
def fasort(categories):
    replacements = (u'پ',u'بي', u'چ' , u'جي', u'ژ',u'زي', u'ک',u'قي', u'گ',u'كي', u'۱',u'z۱', u'۲',u'z۲', u'۳',u'z۳', u'۴',u'z۴', u'۵',u'z۵', u'۶',u'z۶', u'۷',u'z۷', u'۸',u'z۸', u'۹',u'z۹', u'۰',u'z۰')
    items,newsort=[],[]
    for catory in categories:
        old_catory=catory
        for i in range(0,len(replacements)-1,2):
            catory=str(catory).replace(replacements[i],replacements[i+1])
        items.append([old_catory,catory])
    items.sort(lambda x, y: cmp(x[1],y[1]))
    for item in items:
        newsort.append(item[0])
        print item[0]
    return newsort
def faToEn(faTxt, type):
  # changing english to farsi numbers
  faChrsToFrcRplc = u'۰۱۲۳۴۵۶۷۸۹«»٬٫٪،؛؟'
  enChrsToFrcRplc = u'0123456789""`.%,;?'
  if type is 'force':
    for i in range(0,18):
      enTxt = faTxt.replace(enChrsToFrcRplc[i], faChrsToFrcRplc[i])
  elif type is 'safe':
    pass
  return enTxt

def fixCsmtc(faTxt, type):
    # ZWNJ
    if type is 'force':
        txt = re.sub(u'‌{2,}', u'‌', txtTmp) # پشت‌سرهم
        txt = re.sub(u'\[\[([^\]\|]*?)‌]](%s+)' % faChrs, ur'[[\1|\1\2]]', txt) # Piping
        txt = re.sub(u'‌(?![ئاآأإژزرذدوؤةبپتثجچحخسشصضطظعغفقکگلمنهیيًٌٍَُِّْٰٓٔ]|[\u0900-\u097F]|ֹ)', '', txt) # در پس
        txt = re.sub(u'(?<![ئبپتثجچحخسشصضطظعغفقکگلمنهیيًٌٍَُِّْٰٓٔ]|[\u0900-\u097F]|f|ֹ)‌', '', txt) # در پیش
    elif type is 'safe':
        ###
        a=1
    return enTxt

def run(generator):
        for page in generator: 
            try:
                if not page.canBeEdited():
                    wikipedia.output( u'Skipping locked page %s' % page.title() )
                    continue
                text_fa = page.get()#------------------------------geting pages content
            except wikipedia.NoPage:
                wikipedia.output( u'Page %s not found' % page.title() )
                continue
            except wikipedia.IsRedirectPage:#----------------------geting pages redirects contents
                 pageRedirect = page.getRedirectTarget()
                 text_fa = pageRedirect.get()
                 wikipedia.output( u'Page %s was Redirect but edited!' %  pageRedirect )                
            except:
                 continue
            
            new_text=BotRun(page,text_fa)
            savepart( page,new_text )#---------------saving changes in page with new_text content-----------------------------------


def savepart( page,new_text):
     if new_text!=None and page!=None and new_text.find( u'#تغییرمسیر')==-1 and  new_text.find( u'#ridirect')==-1 and  new_text.find( u'#Ridirect')==-1:
            try:
                page.put( new_text,msg % page ,watchArticle = None,minorEdit = True)
            except wikipedia.EditConflict:
                wikipedia.output( u'Skipping %s because of edit conflict' % ( page.title() ) )
            except wikipedia.SpamfilterError,url:
                wikipedia.output( u'Cannot change %s because of blacklist entry %s' % ( page.title(),url ) )

def main():
    summary_commandline,template,gen = None,None,None
    exceptions,PageTitles,namespaces = [],[],[]
    autoText,autoTitle = False,False
    genFactory = pagegenerators.GeneratorFactory()
    wikipedia.setAction( msg )
    arg=False#------if you dont want to work with arguments leave it False if you want change it to True---
    if arg==True:
        for arg in wikipedia.handleArgs():
            if arg == '-autotitle':
                autoTitle = True
            elif arg == '-autotext':
                autoText = True
            elif arg.startswith( '-page:' ):
                if len(arg) == 6:
                    PageTitles.append(wikipedia.input( u'Which page do you want to chage?' ))
                else:
                    PageTitles.append(arg[6:])
            elif arg.startswith( '-cat:' ):
                if len(arg) == 5:
                    PageTitles.append(wikipedia.input( u'Which Category do you want to chage?' ))
                else:
                    PageTitles.append('Category:'+arg[5:])
            elif arg.startswith( '-template:' ):
                if len(arg) == 10:
                    PageTitles.append(wikipedia.input( u'Which Template do you want to chage?' ))
                else:
                    PageTitles.append('Template:'+arg[10:])
            elif arg.startswith('-except:'):
                exceptions.append(arg[8:])
            elif arg.startswith( '-namespace:' ):
                namespaces.append( int( arg[11:] ) )
            elif arg.startswith( '-ns:' ):
                namespaces.append( int( arg[4:] ) )
            elif arg.startswith( '-summary:' ):
                wikipedia.setAction( arg[9:] )
                summary_commandline = True
            else:
                generator = genFactory.handleArg(arg)
                if generator:
                    gen = generator
    else:
        PageTitles = [raw_input(u'Page:> ').decode('utf-8')]
        
    if PageTitles:
        pages = [wikipedia.Page(faSite,PageTitle) for PageTitle in PageTitles]
        gen = iter( pages )
    if not gen:
        wikipedia.stopme()
        
    if namespaces != []:
        gen = pagegenerators.NamespaceFilterPageGenerator( gen,namespaces )
    preloadingGen = pagegenerators.PreloadingGenerator( gen,pageNumber = 60 )#---number of pages that you want load at same time
    run(preloadingGen)
 
if __name__ == "__main__":
    try:
        main()
    finally:
        wikipedia.stopme()

بخش پایین

ویرایش