حالت آفلاین — محتوا از حافظهٔ کش نمایش داده می‌شود

شمارش کلمات داخل فایل

تمرین آسان 1054 visibility link download flag

برنامه ای بنویسید که یک فایل متنی را بخواند ،تعداد کلمات آن را بشمارد و تعداد کلمات را در یک فایل جدید بنویسد.

reply 5

visibility
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')
پاسخ هوش مصنوعی Ai Python
newfile = open('file.txt','r+')
char = input("Enter Word To Search :")
context = newfile.read()
words_count = context.split()
print(len(words_count))
if char in context:
    print('True')
else:
    print('False!')

ارسال جواب

جوابت را با Markdown بنویس و ثبت کن

×
بستن