示例#1
0
def appendtext(page, apptext, always):
    if page.isRedirectPage():
        page = page.getRedirectTarget()
    if not page.exists():
        if page.isTalkPage():
            text = u''
        else:
            raise pywikibot.NoPage(u"Page '%s' does not exist" % page.title())
    else:
        text = page.text
    # Here you can go editing. If you find you do not
    # want to edit this page, just return
    oldtext = text
    text += apptext
    if text != oldtext:
        pywikibot.showDiff(oldtext, text)
        if not always:
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?', ['Yes', 'No', 'All'],
                'yNa', 'N')
            if choice == 'a':
                always = True
        if always or choice == 'y':
            page.text = text
            page.save(i18n.translate(pywikibot.Site(), comment, fallback=True))
示例#2
0
def lookup_county(town):
    """Look up the county for a given town from its Wikipedia article.

    The 'town' argument should be the name of a Wikipedia
    article for a town or city.  lookup_county will load this
    article, look for {{Infobox settlement}} and will see if
    a county is named in one of the 'subdivision_name' parameters,
    and will return that county name if so.

    If no Wikipedia article exists for this town, or if the article
    does not have a matching infobox, or if the infobox does not
    mention a county, None is returned.
    """
    try:
        townpage = pywikibot.Page(pywikibot.Site(), town).get()
    except pywikibot.NoPage():
        return None

    w = mw.parse(townpage)
    for t in w.filter_templates():
        if t.name.strip_code() == 'Infobox settlement':
            # Find the subdivision_name parameters and
            # look for one that names a county
            params = [
                p for p in t.params if p.name.find('subdivision_name') > -1
            ]
            for p in params:
                c = p.value.filter_wikilinks(matches='County,')
                if c:
                    return c[0].title
示例#3
0
def main():
    index = None
    djvu = None
    pages = None
    # what would have been changed.
    ask = False
    overwrite = 'ask'

    # Parse command line arguments
    for arg in pywikibot.handleArgs():
        if arg.startswith("-ask"):
            ask = True
        elif arg.startswith("-overwrite:"):
            overwrite = arg[11:12]
            if overwrite != 'y' and overwrite != 'n':
                pywikibot.output(
                    u"Unknown argument %s; will ask before overwriting" % arg)
                overwrite = 'ask'
        elif arg.startswith("-djvu:"):
            djvu = arg[6:]
        elif arg.startswith("-index:"):
            index = arg[7:]
        elif arg.startswith("-pages:"):
            pages = arg[7:]
        else:
            pywikibot.output(u"Unknown argument %s" % arg)

    # Check the djvu file exists
    if djvu:
        os.stat(djvu)

        if not index:
            import os.path
            index = os.path.basename(djvu)

    if djvu and index:
        site = pywikibot.getSite()
        index_page = pywikibot.Page(site, index)

        if site.family.name != 'wikisource':
            raise pywikibot.PageNotFound(
                u"Found family '%s'; Wikisource required." % site.family.name)

        if not index_page.exists() and index_page.namespace() == 0:
            index_namespace = site.mediawiki_message(
                'Proofreadpage index namespace')

            index_page = pywikibot.Page(pywikibot.getSite(),
                                        u"%s:%s" % (index_namespace, index))
        if not index_page.exists():
            raise pywikibot.NoPage(u"Page '%s' does not exist" % index)
        pywikibot.output(u"uploading text from %s to %s"
                         % (djvu, index_page.title(asLink=True)))
        bot = DjVuTextBot(djvu, index, pages, ask, overwrite)
        if not bot.has_text():
            raise ValueError("No text layer in djvu file")
        bot.run()
    else:
        pywikibot.showHelp()
示例#4
0
    def append_text(self, page, apptext):
        if page.isRedirectPage():
            page = page.getRedirectTarget()
        if page.exists():
            text = page.text
        else:
            if page.isTalkPage():
                text = u''
            else:
                raise pywikibot.NoPage(u"Page '%s' does not exist" % page.title())

        oldtext = text
        text += apptext
        self.userPut(page, oldtext, text, comment=self.summary)
示例#5
0
    def append_text(self, page, apptext):
        """Append apptext to the page."""
        if page.isRedirectPage():
            page = page.getRedirectTarget()
        if page.exists():
            text = page.text
        else:
            if page.isTalkPage():
                text = ''
            else:
                raise pywikibot.NoPage(page)

        text += apptext
        self.current_page = page
        self.put_current(text)
示例#6
0
    def append_text(self, page, apptext):
        """Append apptext to the page."""
        if page.isRedirectPage():
            page = page.getRedirectTarget()
        if page.exists():
            text = page.text
        else:
            if page.isTalkPage():
                text = u''
            else:
                raise pywikibot.NoPage(page)

        oldtext = text
        text += apptext
        self.userPut(page, oldtext, text, summary=self.summary)
示例#7
0
文件: ksp_util.py 项目: xZise/bobbot
def get_part_infobox(site, part_name):
    box_page = pywikibot.page.Page(site, part_name + u"/Box")
    box_infobox, box_parsed = extract_from_page(box_page)
    part_page = pywikibot.page.Page(site, part_name)
    part_infobox, part_parsed = extract_from_page(part_page)
    if not box_page.exists():
        if not part_page.exists():
            raise pywikibot.NoPage(box_page)
        print("WARNING: The infobox page {} does not exist.".format(
            box_page.title()))
    # only one must be defined
    if not box_infobox and not part_infobox:
        print("ERROR: Neither the part nor box page contain an infobox.")
        return (None, box_page, box_parsed)
    elif box_infobox and part_infobox:
        print("ERROR: Both part and box page contin an infobox.")
        return (None, box_page, box_parsed)
    else:
        return (box_infobox
                or part_infobox, box_page if box_infobox else part_infobox,
                box_parsed if box_infobox else part_parsed)
示例#8
0
def get_media_identifier(file_page):
    """
    Resolve the file page target and return the corresponding Mid.

    If the file page is a redirect then return the Mid corresponding to the
    redirection target.

    @param file_page: pywikibot.FilePage object.
    @return The Mid media identifier.
    @raises: pywikibot.NoPage
    """
    if file_page.isRedirectPage():
        old_title = file_page.title()
        file_page = file_page.getRedirectTarget()
        pywikibot.log(
            '{0} - Was a redirect, editing the target "{1}" instead.'.format(
                old_title, file_page.title()))

    if not file_page.exists():
        raise pywikibot.NoPage(file_page)

    return 'M{}'.format(file_page.pageid)
示例#9
0
def main(*args: Tuple[str, ...]):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    """
    index = None
    djvu_path = '.'  # default djvu file directory
    pages = '1-'
    options = {}

    # Parse command line arguments.
    local_args = pywikibot.handle_args(args)
    for arg in local_args:
        if arg.startswith('-index:'):
            index = arg[7:]
        elif arg.startswith('-djvu:'):
            djvu_path = arg[len('-djvu:'):]
        elif arg.startswith('-pages:'):
            pages = arg[7:]
        elif arg.startswith('-summary:'):
            options['summary'] = arg[len('-summary:'):]
        elif arg == '-force':
            options['force'] = True
        elif arg == '-always':
            options['always'] = True
        else:
            pywikibot.output('Unknown argument ' + arg)

    # index is mandatory.
    if not index:
        pywikibot.bot.suggest_help(missing_parameters=['-index'])
        return

    # If djvu_path is not a file, build djvu_path from dir+index.
    djvu_path = os.path.expanduser(djvu_path)
    djvu_path = os.path.abspath(djvu_path)
    if not os.path.exists(djvu_path):
        pywikibot.error('No such file or directory: ' + djvu_path)
        return
    if os.path.isdir(djvu_path):
        djvu_path = os.path.join(djvu_path, index)

    # Check the djvu file exists and, if so, create the DjVuFile wrapper.
    djvu = DjVuFile(djvu_path)

    if not djvu.has_text():
        pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
        return

    # Parse pages param.
    pages = pages.split(',')
    for interval in range(len(pages)):
        start, sep, end = pages[interval].partition('-')
        start = 1 if not start else int(start)
        if not sep:
            end = start
        else:
            end = int(end) if end else djvu.number_of_images()
        pages[interval] = (start, end)

    site = pywikibot.Site()
    if not site.has_extension('ProofreadPage'):
        pywikibot.error(
            'Site {} must have ProofreadPage extension.'.format(site))
        return

    index_page = pywikibot.Page(site, index, ns=site.proofread_index_ns)

    if not index_page.exists():
        raise pywikibot.NoPage(index)

    pywikibot.output('uploading text from {} to {}'.format(
        djvu.file, index_page.title(as_link=True)))

    bot = DjVuTextBot(djvu, index_page, pages, **options)
    bot.run()