شمارش کلمات داخل فایل
برنامه ای بنویسید که یک فایل متنی را بخواند ،تعداد کلمات آن را بشمارد و تعداد کلمات را در یک فایل جدید بنویسد.
👨💻 7 ساعت قبل کاربر ناشناس این تمرین رو مشاهده کرد
برنامه ای بنویسید که یک فایل متنی را بخواند ،تعداد کلمات آن را بشمارد و تعداد کلمات را در یک فایل جدید بنویسد.
from pathlib import Path
path = rf"{input("Enter the path : ")}"
words = Path(path).read_text()
total = 0
for x in words:
if x == " " or x == "." or x == "!" or x == "?":
total += 1
print(f"The words count is : {total}"))
with open('input.txt','r') as file:
text = file.read()
words = text.split()
word_count = len(words)
with open('output.txt','w') as file:
file.write(f"{word_count}")
print(word_count)
def count_words_in_file(input_filename, output_filename):
try:
with open(input_filename, 'r', encoding='utf-8') as file:
text = file.read()
# شمارش کلمات (تقسیم متن بر اساس فاصلهها)
words = text.split()
word_count = len(words)
# نوشتن نتیجه در فایل خروجی
with open(output_filename, 'w', encoding='utf-8') as file:
file.write(f"تعداد کلمات فایل '{input_filename}': {word_count}\n")
print(f"تعداد کلمات: {word_count} در فایل '{output_filename}' ذخیره شد.")
except FileNotFoundError:
print(f"فایل '{input_filename}' پیدا نشد.")
except Exception as e:
print(f"خطا رخ داد: {e}")
def count_words(input_file, output_file):
with open(input_file, 'r', encoding='utf-8') as f:
text = f.read()
word_count = len(text.split())
with open(output_file, 'w', encoding='utf-8') as f:
f.write(f'Number of words: {word_count}')
count_words('input.txt', 'output.txt')
برای استفاده از این بخش باید وارد حساب کاربریت بشی
ورود/ثبت نام