Bikarhêner:Şêr/cure-rastker.py

import pywikibot
import re

def get_links_from_text(text):
    # Find links within double square brackets
    links = re.findall(r'\[\[([^|\]]+)(?:\|[^|\]]+)?\]\]', text)
    return links

def check_category_existence(title, category_name):
    site = pywikibot.Site("ku", "wiktionary")
    page = pywikibot.Page(site, title)
    categories = page.categories()
    for cat in categories:
        if category_name in cat.title():
            return True
    return False

def check_section_content(page, section_title):
    page_text = page.text
    section_regex = re.compile(r'==+\s*([^=]+?)\s*==+', re.MULTILINE)
    sections = section_regex.findall(page_text)
    return section_title in sections

def replace_text_content(page, old_text, new_text):
    text = page.text
    new_text = text.replace(old_text, new_text)
    page.text = new_text
    page.save(summary='Cure Lêker hat lêzêdekirin', botflag=True)

site = pywikibot.Site("ku", "wiktionary")  
category_name = "Gotarên bê kategoriya rêzimanî bi farisî"
category = pywikibot.Category(site, f"Category:{category_name}")
titles = [page.title() for page in category.articles()]

section_title = "=== Lêker ==="
target_category = "Lêker bi kurmancî"
for title in titles:
    if check_category_existence(title, target_category):
        page = pywikibot.Page(site, title)
        page_content = page.text
        links = get_links_from_text(page_content)
        for link in links:
            if check_section_content(page, section_title):
                print(f'The link "{link}" contains the section "{section_title}".')
                replace_text_content(page, "=== Mane ===\n{{bêcure|fa}}", "=== Lêker ===\n{{lêker|fa}}")
            else:
                print(f'The link "{link}" does not contain the section "{section_title}".')