تمرين إعادة البناء
Text File Line Counter
أعد كتابة سكربت Python يحسب الأسطر والكلمات والحروف في ملفات نصية.
python
~10 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
import argparse
from pathlib import Path
def count_text(path: Path) -> tuple[int, int, int]:
text = path.read_text(encoding="utf-8")
lines = text.count("\n") + (1 if text and not text.endswith("\n") else 0)
words = len(text.split())
chars = len(text)
return lines, words, chars
def main() -> None:
parser = argparse.ArgumentParser(description="Count lines, words, and characters.")
parser.add_argument("files", nargs="+", help="Text files to count")
args = parser.parse_args()
total_lines = total_words = total_chars = 0
for name in args.files:
path = Path(name)
try:
lines, words, chars = count_text(path)
except OSError as error:
print(f"{path}: {error}")
continue
except UnicodeDecodeError:
print(f"{path}: not a UTF-8 text file")
continue
total_lines += lines
total_words += words
total_chars += chars
print(f"{lines:6} {words:6} {chars:6} {path}")
if len(args.files) > 1:
print(f"{total_lines:6} {total_words:6} {total_chars:6} total")
if __name__ == "__main__":
main()اكتب هنا