Example #1
0
 def action(self, page, **kwargs):
     super(SelectTplsWithMojo, self).action(page, **kwargs)
     tpl_title = page.title[len(u'Шаблон:'):]
     if u'/Документация' in tpl_title:
         return
     content = page.content
     redirect = page.page_redirect.redirect
     if redirect:
         return
     rod = re.search(u'\|(\s*род.*)\n', content)
     if not rod:
         return
     rod_value = rod.group(1)
     if tpl_title.startswith(u'сущ ru m '):
         new_rod = u'муж'
     elif tpl_title.startswith(u'сущ ru n '):
         new_rod = u'ср'
     else:
         return
     if True:  # rod_value == u'род={{#switch:{{{можо}}}|мо=муж|можо=общ|жен}}':
         # if tpl_title not in selected_tpls:
         #     return
         new_content = content.replace(u"|%s\n" % rod_value,
                                       u'|род={{{род|%s}}}\n' % new_rod)
         if content != new_content:
             desc = u'Для преобразования параметра "можо" в "род" в статьях (для soshial)'
             save_wiki_page(page.title, new_content, desc, wait=5)
         selected_tpls.append(tpl_title)
def get_unknown_inflection_simple():
    items = WordInflection.objects.filter(kind__in=[u'f ?', u'm ?', u'n ?'])
    words = sorted(items, key=lambda item: item.word[::-1])
    report = dict()
    for word in words:
        print word.word
        valid_num = check_correct_inflection(word.word, word.gender)
        if valid_num < 0:
            continue
        key = "%s%d" % (word.gender, valid_num)
        report.setdefault(key, list())
        report[key].append((word.word, word.content))

    file_path = join(PAGES_DIR, u'Массовое редактирование (simple)')
    wiki_prefix = u"Участник:Vitalik/Массовое редактирование/Словоизменение/сущ/simple"
    # desc = u"Полное обновление данных"
    desc = u"Создание списков для массового редактирования"
    for key in report.keys():
        print key
        items = report.get(key)
        content = gen_report_simple(items, key[0], key[1])
        filename = "%s.txt" % (key)
        print filename
        debug_write(file_path, filename, content)
        # sys.exit()
        wiki_title = "%s/%s" % (wiki_prefix, key)
        save_wiki_page(wiki_title, content, desc)
Example #3
0
def create_index(data, path, desc, debug=True, push=False, use_other=True,
                 alphabet=None, force_wiki_title=None):
    builder = ReversedIndexBuilder(data.keys(), 'ru', data, alphabet=alphabet)

    # for letter in sorted(builder.counts_1.keys(), cmp=wiki_cmp):
    #     print letter, builder.counts_1[letter]
    # for letter in sorted(builder.counts_2.keys(), cmp=wiki_cmp):
    #     print letter, builder.counts_2[letter]

    if debug:
        folders = path.split('/')
        subpath = PAGES_DIR
        for folder in folders:
            subpath = join(subpath, folder)
            if not exists(subpath):
                mkdir(subpath)

    file_path = join(PAGES_DIR, path)

    wiki_prefix = u"Участник:Vitalik"

    letters = alphabet
    if use_other:
        letters += '-'

    for letter in letters:
        title_letter = "-%s" % letter.lower()
        print title_letter
        content = builder.get(letter)
        # letter = ur(letter)
        if debug:
            debug_write(file_path, title_letter, content)
        if push:
            if force_wiki_title:
                wiki_title = force_wiki_title
            else:
                wiki_title = "%s/%s" % (wiki_prefix, path)
            wiki_title = "%s/%s" % (wiki_title, title_letter)
            save_wiki_page(wiki_title, content, desc)
        # sleep(1)
        # break
    # exit()

    for letter, pages in builder.separate_pages.items():
        for page in sorted(pages, key=lambda x: len(x)):
            title_page = "-%s" % page.lower()[::-1]
            print title_page
            if not use_other and page[0] == '-':
                continue
            content = builder.get(page)
            # page = ur(page)
            if debug:
                debug_write(file_path, title_page, content)
            if push:
                if force_wiki_title:
                    wiki_title = force_wiki_title
                else:
                    wiki_title = "%s/%s" % (wiki_prefix, path)
                wiki_title = "%s/%s" % (wiki_title, title_page)
                save_wiki_page(wiki_title, content, desc)
Example #4
0
 def action(self, page, **kwargs):
     content = kwargs['content']
     parts = re.findall('(^|\n)(=[^=\n]+=)\n', content)
     for part in parts:
         found = part[1]
         if found in [u'= Буква (латиница) =', u'= Буква (кириллица) =']:
             continue
         # print "* [[%s]]: <code><nowiki>%s</nowiki></code>" % (page.title, found)
         m = re.match(u'^= *\{\{-(?P<lang>[-a-z]+|Праславянский)-(?P<remove>\|([^}]+|\{\{PAGENAME\}\}|))?\}\} *=$',
                      found, re.IGNORECASE)
         if not m:
             print found
         if m:
             remove = m.group('remove')
             # if remove:
             #     print page.title, remove
             if remove == '|nocat':
                 continue
             lang = m.group('lang')
             # print "* %s: %s" % (page.title, lang)
             if lang != 'ru':
                 continue
             old_header = m.group(0)
             new_header = "= {{-%s-}} =" % lang
             if old_header == new_header:
                 continue
             self.changed += 1
             print dt(), 'changed:', self.changed
             wiki_content = get_wiki_page_content(page.title)
             new_wiki_content = wiki_content.replace(old_header, new_header)
             save_wiki_page(page.title, new_wiki_content,
                            "викификация заголовка первого уровня",
                            wait=5)
Example #5
0
    def action(self, page, **kwargs):
        super(PoslovitsyReplacer4, self).action(page, **kwargs)
        # print '=' * 80
        if ':' in page.title:
            return
        old_content = page.content
        # new_content = re.sub(
        #     u'\n=== Фразеологизмы и устойчивые сочетания ===\n([^=]*)=== Пословицы ===\n',
        #     u'\n=== Фразеологизмы и устойчивые сочетания ===\n\\1==== Пословицы и поговорки ====\n',
        #     old_content
        # )
        # if old_content != new_content:
        #     desc = u'Перемещение раздела "Пословицы" в "Фразеологизмы и устойчивые словосочетания"'
        #     save_wiki_page(page.title, new_content, desc, wait=5)
        #     # self.stop()
        # else:
        #     print u'×××'

        if u'=== Фразеологизмы и устойчивые сочетания ===' not in old_content:
            new_content = re.sub(
                u'\n=== Пословицы ===\n',
                u'\n=== Фразеологизмы и устойчивые сочетания ===\n\n==== Пословицы и поговорки ====\n',
                old_content
            )
            if old_content != new_content:
                desc = u'Перемещение раздела "Пословицы" в создаваемый "Фразеологизмы и устойчивые словосочетания"'
                save_wiki_page(page.title, new_content, desc, wait=5)
                # self.stop()
            else:
                print u'×××'
Example #6
0
 def tpl_action(self, page, old_tpl, title, morph, lang, params, tail,
                pre_tail):
     new_tpl = self.make_changes(page, old_tpl, title, morph, lang, params,
                                 tail, pre_tail)
     if new_tpl == old_tpl:  # tpl doesn't change
         return
     print 'changing'
     # return
     try:
         if self.debug:
             old_content = page.content
         else:
             old_content = get_wiki_page_content(page.title)
     except IsRedirectPage:
         return
     new_content = old_content.replace(old_tpl, new_tpl)
     if old_content == new_content:  # content doesn't change
         print "It's strange: content doesn't change in '%s'!" % \
             page.title.encode('cp1251')
         return
     if self.debug:
         print '-' * 80
         print new_content
     else:
         save_wiki_page(page.title, new_content, self.desc, wait=5)
 def action(self, page, **kwargs):
     # print '=' * 80
     # print dt(), page.title
     content = kwargs['content']
     m = re.search(u'=== Смотреть также ===\n([^={]*)', content, flags=re.MULTILINE | re.DOTALL)
     if m:
         block_content = m.group(1)
         # print block_content.strip()
         for remove in removings:
             if remove in block_content:
                 print '=' * 80
                 print dt(), page.title
                 print block_content.strip()
                 old_content = get_wiki_page_content(page.title)
                 new_content = re.sub(
                     u'=== Смотреть также ===\n\s*%s\n' % remove.replace('*', r'\*').replace('[', r'\[').replace(']', r'\]'),
                     u'', old_content)
                 if old_content != new_content:
                     desc = u'Удаление "Смотреть также" со списком имён'
                     save_wiki_page(page.title, new_content, desc, wait=5)
                     print 'saved'
                 else:
                     print 'not changed'
     else:
         print u'×××'
Example #8
0
 def action(self, page, **kwargs):
     # print page.title
     super(RemoveBad, self).action(page, **kwargs)
     title = page.title
     if ':' in title:
         return
     content = page.content
     if u"{{{" in content:
         print title
         print "%s&section=2" % get_edit_page_url(title)
     return
     # if u"основа1={{{" in content:
     if u"основа={{{" in content:
         print title
         print "%s&section=2" % get_edit_page_url(title)
         try:
             old_content = content
             old_content = get_wiki_page_content(title)
         except IsRedirectPage:
             return
         # new_content = re.sub(u"\|основа\d?=\{\{\{\d\|?\}\}\}(́?\{\{\{\d\|?\}\}\})?\n", '', old_content)
         new_content = re.sub(u"\|основа=\{\{\{\d\|([А-Яа-я]+)\}\}\}\n",
                              u'|основа=\\1\n',
                              old_content)
         new_content = re.sub(u"\|слоги=\{\{\{\d\|([А-Яа-я]+)\}\}\}\n",
                              u'|слоги={{по-слогам|\\1}}\n',
                              new_content)
         if old_content == new_content:  # content doesn't change
             return
         desc = u'Удаление "странных" параметров'
         save_wiki_page(title, new_content, desc, wait=5)
Example #9
0
    def action(self, page, **kwargs):
        super(ReplacePTemplate, self).action(page, **kwargs)
        old_content = kwargs['content']

        # old_content = re.sub(u'[А-Яа-я]+\{\{!\}\}([А-Яа-я\u0301]+)', '\\1', old_content)
        # if '{{!}}' in old_content:
        #     print '###'
        #     return
        p = re.compile(u'(\{\{[pр]\|(?P<w1>[^\|\}]+)\|?((?P<p1>[,;])|&#59(?P<p2>;))?\|?(?P<w2>[^\}\|]*)\|?((?P<p3>[,;])|&#59(?P<p4>;))?\}\})')
        # p = re.compile(u'(\{\{[pр]\|([^|]+)\|?(([,;])|&#59(;))?\|?([^\}\|]*)\}\})')
        #                 '(\{\{[pр]\|([^|]+)\|?(([,;])|&#59(;))?\|?([^\}\|]*)\}\})'
        items = p.findall(old_content)
        if items:
            print
            print page.title
            print
            old_content = get_wiki_page(page.title).get()
            new_content = old_content
            for item in items:
                old_line = item[0]
                new_line = "%s%s%s%s%s%s%s" % \
                           (item[1],  # word1
                            item[3], item[4], ' ' if item[5] else '',
                            item[5],  # word2
                            item[7], item[8],)
                new_content = new_content.replace(old_line, new_line)
            print old_content
            print
            print new_content
            print
            if old_content != new_content:
                desc = u'удаление вызовов шаблона {{p}}'
                save_wiki_page(page.title, new_content, desc, wait=5)
Example #10
0
 def action(self, page, **kwargs):
     super(ReplaceSootvMn, self).action(page, **kwargs)
     content = kwargs['content']
     p = re.compile(
         u"""(?P<tpl>\{\{
             (?P<title>(?P<morph>гл)[ ]ru[ ][^|]+)  # заголовок
             (?P<params>[^{}]+?(\{\{[^{}]+?\}\})?[^{}]+?)  # параметры
             \}\})""",
         flags=re.UNICODE + re.DOTALL + re.VERBOSE)
     parts = p.findall(content)
     for part in parts:
         m = p.search(part[0])
         if m:
             old_tpl = m.group('tpl')
             new_tpl = old_tpl.replace(u"|соотв-мн=", u"|соотв=")
             if new_tpl != old_tpl:
                 old_content = get_wiki_page(page.title).get()
                 # old_content = content
                 new_content = old_content.replace(old_tpl, new_tpl)
                 if old_content != new_content:
                     print page.title
                     print '-' * 100
                     print old_tpl
                     print '-' * 100
                     print new_tpl
                     print '-' * 100
                     # print new_content
                     # print '=' * 200
                     desc = u'замена параметра "|соотв-мн=" на "|соотв="'
                     save_wiki_page(page.title, new_content, desc, wait=5)
Example #11
0
 def after(self):
     super(NewPagesStatistics, self).after()
     self.content += u'|}\n\n'
     self.content += u'[[Категория:Викисловарь:Русский язык]]\n'
     # print self.content
     save_wiki_page(u'Викисловарь:Проект:Русский язык/Новые статьи',
                    self.content,
                    u'Созданные за последние 7 дней')
Example #12
0
 def save_report(self, desc):
     title = u"%s/report" % self.wikt_data_page
     content = get_wiki_page_content(title)
     save_wiki_page(title, content + "\n" + self.report, desc)
     # print '-' * 100
     # print self.report
     # print '-' * 100
     self.report = ''
Example #13
0
 def save_page(self, lang=None, year=None):
     title = u"Участник:Vitalik/Статистика/Авторы"
     if lang:
         title += u"/%s" % lang
     if year:
         title += u"/%s" % year
     content = self.get_content(lang, year)
     desc = u'Генерация статистики по авторам'
     save_wiki_page(title, content, desc)
Example #14
0
def start_report_headers_simple():
    verification = Verification.objects.get(slug='headers_syntax')
    mistakes = Mistake.objects.filter(verification=verification)
    content = u'== Об этом разделе ==\nЗдесь собраны синтаксические ошибки в заголовках\n\n'
    content += u'== Ошибки ==\n\n'
    for mistake in mistakes:
        content += mistake.display + "\n"
    desc = u'Генерация отчёта синтаксических ошибок в заголовках'
    save_wiki_page(u'Участник:Vitalik/Отчёты/Заголовки/Синтаксис', content, desc)
 def section_action(self, page, lang, section_content):
     super(ReplaceOldEmptyMorphoRu, self).section_action(page, lang, section_content)
     title = page.title
     if lang != 'ru':
         return
     m = re.search(u'(=== *Морфологические и синтаксические свойства *=== *(.*?)\n)=',
                   section_content, re.UNICODE | re.DOTALL)
     if not m:
         return
     old_body = m.group(2)
     p = re.compile(
         u"""(\{\{
             (?P<title>морфо\s*)  # заголовок
             \|(?P<params>[^{}]+?(\{\{[^{}]+?\}\})?[^{}]+?)  # параметры
             \}\})""",
         flags=re.UNICODE + re.DOTALL + re.VERBOSE)
     parts = p.findall(old_body)
     new_body = old_body
     for part in parts:
         old_params = part[2]
         params = old_params
         params = re.sub(u'(префд|прист|суфф-?|корень|инф|соед|оконч-?|интер|суффд|частица|постфикс)\d*=', '', params)
         params = re.sub(u'\|', '', params).strip()
         if not params:
             # append_dict_list(self.old_empty_morpho, title, part[0])
             new_body = new_body.replace(part[0], u'{{морфо-ru|}}')
         # params = part[2].strip().split('|')
         # for value in params:
         #     value = value.strip()
         #     if '=' in value:
         #         name, value = value.split('=', 1)
         #     if '-' in value:
         #         append_dict_list(self.morpho_wrong_hyphens, title, part[0])
         #         break
     if old_body != new_body:
         # print '=' * 100
         # print old_body
         # print '-' * 100
         # print new_body
         # print '=' * 100
         old_section_content = section_content
         new_section_content = section_content.replace(old_body, new_body)
         try:
             old_content = get_wiki_page_content(title)
         except NoPage:
             send_wiki_mail(subject="pywikibot.exceptions.NoPage: " + title,
                            message=title)
             return
         except IsRedirectPage:
             send_wiki_mail(
                 subject="pywikibot.exceptions.IsRedirectPage: " + title,
                 message=title)
             return
         new_content = old_content.replace(old_section_content, new_section_content)
         if new_content != old_content:
             desc = u"Замена пустого {{морфо}} на пустой {{морфо-ru}}"
             save_wiki_page(title, new_content, desc)
Example #16
0
 def action(self, page, **kwargs):
     super(SlogiSimpleReplacer5, self).action(page, **kwargs)
     if ':' in page.title:
         return
     old_content = get_wiki_page(page.title).get()
     new_content = old_content.replace(
         u"слоги={{по слогам|||}}",
         u"слоги={{по-слогам|%s}}" % page.title)
     if old_content != new_content:
         desc = u'добавление параметра-заголовка к пустому {{по-слогам|}}'
         save_wiki_page(page.title, new_content, desc, wait=5)
Example #17
0
 def action(self, page, **kwargs):
     super(SlogiSimpleReplacer3, self).action(page, **kwargs)
     if ':' in page.title:
         return
     old_content = get_wiki_page(page.title).get()
     new_content = old_content.replace(
         u"слоги=\n",
         u"слоги={{по-слогам|%s}}\n" % page.title)
     if old_content != new_content:
         desc = u'добавление {{по-слогам}} к пустому "слоги="'
         save_wiki_page(page.title, new_content, desc, wait=5)
Example #18
0
 def action(self, page, **kwargs):
     super(SlogiSimpleReplacer2, self).action(page, **kwargs)
     if ':' in page.title:
         return
     old_content = get_wiki_page(page.title).get()
     new_content = old_content.replace(
         u"слоги={{PAGENAME}}\n",
         u"слоги={{по-слогам|%s}}\n" % page.title)
     if old_content != new_content:
         desc = u'замена {{PAGENAME}} в "слоги=" на {{по-слогам|заголовок}}'
         save_wiki_page(page.title, new_content, desc, wait=5)
Example #19
0
def output(subdirectory, mistakes):
    content = u'== Об этом разделе ==\nЗдесь собраны неизвестные заголовки и списки слов, в которых они встречаются\n\n'
    content += u'<div class="index">\n'
    for mistake in mistakes:
        word = mistake.word#.decode('utf-8')
        content += u'\n== <nowiki>%s</nowiki> (%d) ==\n\n' % (word, mistake.count)
        content += mistake.display + "\n"
    content += u'</div>\n'
    desc = u'Генерация отчёта по неизвестным заголовкам (обновление)'
    # print content
    save_wiki_page(u'Участник:Vitalik/Отчёты/Заголовки/Неизвестные/%s' % subdirectory,
                   content, desc)
Example #20
0
 def lang_action(self, page, lang, content):
     content = page.content
     p = re.compile('\[\[[a-z]{2}:\]\]\n?')
     if p.search(content):
         print page.title
         content = get_wiki_page_content(page.title)
         new_content = p.sub('', content)
         if new_content != content:
             new_content, changed = wikify_headers_spaces(new_content)
             desc = u'Удаление пустышек interwiki'
             save_wiki_page(page.title, new_content, desc, wait=5)
             # self.stop()
     return content
Example #21
0
def create_page(tree, prefix):
    page_title = prefix + tree[0]
    items = tree[1]
    print 'PAGE:', page_title
    page_content = u"Раздел: '''{}'''\n\n".format(tree[0])
    page_content += u"Подразделы:\n"
    page_content += print_list(items)
    print page_content
    print
    save_wiki_page(page_title, page_content, u'Формирование дерева ссылок')
    for item in items:
        if isinstance(item, tuple):
            create_page(item, page_title + '/')
Example #22
0
def report_headers(data, path, desc, debug=True, push=False):
    alphabet = u'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
    # alphabet = None
    builder = HeadersBuilder(data.keys(), 'ru', data, max_words_on_page=500,
                             alphabet=alphabet)

    # for letter in sorted(builder.counts_1.keys(), cmp=wiki_cmp):
    #     print letter, builder.counts_1[letter]
    # for letter in sorted(builder.counts_2.keys(), cmp=wiki_cmp):
    #     print letter, builder.counts_2[letter]

    if debug:
        folders = path.split('/')
        subpath = PAGES_DIR
        for folder in folders:
            subpath = join(subpath, folder)
            if not exists(subpath):
                mkdir(subpath)

    file_path = join(PAGES_DIR, path)

    wiki_prefix = u"Участник:Vitalik"

    # for letter in russian_letters() + ['_']:
    for letter in alphabet + '-':
    # for letter in ['-', u'А', u'Б', u'В', u'Г', ]:
        print letter
        content = builder.get(letter)
        # letter = ur(letter)
        debug_write(file_path, letter, content)
        if push:
            wiki_title = "%s/%s/%s" % (wiki_prefix, path, letter)
            save_wiki_page(wiki_title, content, desc)
        # sleep(1)
        # break
    # exit()

    #todo: делить на 3 буквенные статьи!!!
    for letter, pages in builder.separate_pages.items():
        for page in pages:
            print dt(), page
            if page in [u'Пер', u'Про', u'Под', u'При', u'Раз', u'Рас',
                        u'Пре', u'Пол', u'Кол', u'Мик', u'Кон', u'Ком']:
                print u'→ too big!'
                continue
            content = builder.get(page)
            # page = ur(page)
            debug_write(file_path, page, content)
            if push:
                wiki_title = "%s/%s/%s" % (wiki_prefix, path, page)
                save_wiki_page(wiki_title, content, desc)
Example #23
0
 def lang_action(self, page, lang, content):
     content = page.content
     if u'{{Cf|Индекс:Русский язык/Женские имена}}' in content:
         print page.title
         content = get_wiki_page_content(page.title)
         new_content = content.replace(
             u'==== Значение ====\nЖенское имя\n{{Cf|Индекс:Русский язык/Женские имена}}',
             u'==== Значение ====\n# Женское имя {{пример|}}')
         if new_content != content:
             new_content, changed = wikify_headers_spaces(new_content)
             desc = u'Удаление {{Cf|Индекс:Русский язык/Женские имена}} из раздела "Значение"'
             save_wiki_page(page.title, new_content, desc, wait=5)
             # self.stop()
     return content
Example #24
0
    def make_change(self, title, old_content, new_content):
        if new_content != old_content:
            if not self.report_name:
                raise Exception('Need `report_name` file')
            desc = self.change_description()
            new_content = self.additional_change_content(new_content)
            save_wiki_page(title, new_content, desc, wait=5)

            # todo: create special function for this:
            d = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            append_file(os.path.join(settings.FILES_PATH, 'reports',
                                     self.report_name),
                        "%s: %s" % (d, title),
                        encode='utf-8')
Example #25
0
 def lang_action(self, page, lang, content):
     content = page.content
     p = re.compile('\[\[(?:\w{2,3}|zh-min-nan):(?:[^]]+)\]\]')
     parts = p.findall(content)
     for part in parts:
         if p.search(content):
             print page.title
             content = get_wiki_page_content(page.title)
             new_content = p.sub('', content)
             if new_content != content:
                 new_content, changed = wikify_headers_spaces(new_content)
                 desc = u'Удаление пустышек interwiki'
                 save_wiki_page(page.title, new_content, desc, wait=5)
                 # self.stop()
     return content
Example #26
0
def output_slovoforms():
    print 'output_slovoforms()'
    forms = dict()
    forms_list = WordForm.objects.all()
    print dt(), 'processing forms...'
    for form in forms_list:
        title, base, value, template = \
            form.title, form.base, form.value, form.template
        forms.setdefault(title, dict())
        forms[title].setdefault(value, list())
        forms[title][value].append((base, template))

    i = 1
    n = 1
    content = ''
    for title, items in sorted(forms.items(), key=itemgetter(0)):
        content += u"\n'''[[%s]]''':\n" % title
        for value, templates in items.items():
            # content += u"'''[[%s]]'''\n" % value
            templates = set(templates)
            if len(templates) > 1:
                content += u"\n''(возможно омоформа, ошибка или просто несколько способов получения, обработаем позже и иначе)''\n\n"
                continue
            for base, template in templates:
                template = template.strip()
                if u'|деепр=1' in template:
                    content += u"\n''(деепричастия будут обработаны позже и иначе)''\n\n"
                    continue
                if u'|прич=1' in template:
                    content += u"\n''(причастия будут обработаны позже и иначе)''\n\n"
                    continue
                # lines = ([u'#перенаправление [[%s]]' % base] +
                #          template.split('\n') +
                #          [u'{{пример}}'])
                template = u"= {{-ru-}} =\n\n%s {{пример|}}" % template
                lines = template.split('\n')
                lines = map(lambda x: u" <nowiki>%s</nowiki>" % x, lines)
                content += '\n'.join(lines) + '\n'
        if not i % 200:
            save_wiki_page(u"Участник:Vitalik/Словоформы/v2/А3/%s" % n, content,
                           u"Обновление списка словоформ")
            # print content
            content = ''
            n += 1
            # return
        i += 1
    save_wiki_page(u"Участник:Vitalik/Словоформы/v2/А3/%s" % n, content,
                   u"Обновление списка словоформ")
Example #27
0
 def update_section_pages(self, debug=False):
     if not self.prefix:
         raise Exception(u'Field "prefix" cannot be empty')
     for item in self.iterate_sections():
         page_title = item.get_page_title()
         page_content = item.get_page_content()
         desc = u'Обновление дерева отчётов'
         # print page_title
         if debug:
             print '=' * 10
             print page_title
             print '-' * 10
             print page_content
             print '-' * 10
         else:
             save_wiki_page(page_title, page_content, desc)
Example #28
0
    def action(self, page, **kwargs):
        super(ReplaceBadSootv, self).action(page, **kwargs)
        old_content = kwargs['content']
        if ':' in page.title:
            return

        print "# [[%s]]" % page.title
        # print
        old_content = get_wiki_page(page.title).get()
        new_content = old_content.replace(
            u'}}\nСоответствующий глагол совершенного вида — ?.',
            u'|соотв=\n}}'
        )
        if old_content != new_content:
            desc = u'замена строки "Соответствующий глагол совершенного вида — ?." на пустой параметр "|соотв="'
            save_wiki_page(page.title, new_content, desc, wait=5)
Example #29
0
 def action(self, page, **kwargs):
     super(FindSootv, self).action(page, **kwargs)
     content = kwargs['content']
     p = re.compile(
         u"""(?P<tpl>\{\{
             (?P<title>(?P<morph>гл)[ ]ru[ ][^|]+)  # заголовок
             (?P<params>[^{}]+?(\{\{[^{}]+?\}\})?[^{}]+?)  # параметры
             \}\})""",
         flags=re.UNICODE + re.DOTALL + re.VERBOSE)
     parts = p.findall(content)
     for part in parts:
         m = p.search(part[0])
         if m:
             tpl = m.group('tpl')
             # print tpl
             m2 = re.search(u"\|(соотв)=(?P<value>[^\n]+)\n", tpl)
             if m2:
                 value = m2.group('value')
                 # print m2.group(1)
                 # value = m2.group(0)
                 value = value.strip() if value else ''
                 # print u"* '''%s''' — %s" % (page.title, value)
                 prefixes = [u'приставочного типа ', u'приставочные вида ',
                             u'приставочные типа ', u'приставочные: ',
                             u'приставочный вида ', u'приставочного типа: ',
                             u'<span>приставочные типа</span> ',
                             u'приставочные глаголы типа ',
                             u'приставочные вроде ', u'приставочные ',]
                 for prefix in prefixes:
                     if value.startswith(prefix):
                         old_content = get_wiki_page(page.title).get()
                         # old_content = content
                         new_content = old_content.replace(
                             u'|соотв=%s' % prefix,
                             u'|соотв={{без ссылок|приставочные типа}} ')
                         if old_content != new_content:
                             print page.title
                             # print '-' * 100
                             # print old_tpl
                             # print '-' * 100
                             # print new_tpl
                             # print '-' * 100
                             # print new_content
                             # print '=' * 200
                             desc = u'добавление шаблона "без ссылок" для "приставочного типа" в параметре "соотв"'
                             save_wiki_page(page.title, new_content, desc, wait=5)
                         break
Example #30
0
 def save_report(self, title, description, body, count):
     content = u"== Описание отчёта ==\n" \
               u"%s\n\n" \
               u"Обсуждение всех отчётов " \
               u"'''[[Обсуждение Викисловаря:Отчёты|здесь]]'''.\n\n" \
               u"== Содержимое отчёта ==\n" \
               u"%s\n" \
               u"\n[[Категория:Викисловарь:Отчёты]]" % \
               (description.strip(), body)
     self.tree.add_node(title, count)
     desc = u'Формирование отчёта: {} элемент(ов)'.format(count or u'нет')
     # print '>>', title, count
     print u'Count: ', count
     # print '=' * 100
     # print content
     # print '=' * 100
     save_wiki_page(self.prefix + "/" + title, content, desc)