AzLearn

تمرين إعادة البناء

تحويل حالة النص

أعد كتابة أداة Python تقرأ ملف نص وتحوله إلى UPPER أو lower أو Title أو CamelCase.

python ~12 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
import argparse
import re
from pathlib import Path


def to_camel_case(text: str) -> str:
    words = re.findall(r"[A-Za-z0-9]+", text)
    if not words:
        return ""
    first, *rest = words
    return first.lower() + "".join(word.capitalize() for word in rest)


def convert_text(text: str, style: str) -> str:
    if style == "upper":
        return text.upper()
    if style == "lower":
        return text.lower()
    if style == "title":
        return text.title()
    if style == "camel":
        return to_camel_case(text)
    raise ValueError(f"Unknown style: {style}")


def output_path(source: Path, style: str) -> Path:
    return source.with_name(f"{source.stem}_{style}{source.suffix}")


def main() -> None:
    parser = argparse.ArgumentParser(description="Convert text file casing.")
    parser.add_argument("file", type=Path)
    parser.add_argument("style", choices=["upper", "lower", "title", "camel"])
    parser.add_argument("--output", type=Path)
    args = parser.parse_args()

    text = args.file.read_text(encoding="utf-8")
    converted = convert_text(text, args.style)
    target = args.output or output_path(args.file, args.style)
    target.write_text(converted, encoding="utf-8")
    print(f"Wrote: {target}")


if __name__ == "__main__":
    main()
اكتب هنا