CodeSolved

Solved Programming Questions & Exercises

Count the words inside the file

Practice Easy 1754/ Download 417 Views

Write a program to read a text file, count the number of words, and write the number of words in a new file.

3 Answers

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}"))
Yasin.hn Download Python
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) 
Imanm Download Python
def count_words_in_file(input_filename, output_filename):
    try:
        with open(input_filename, 'r', encoding='utf-8') as file:
            text = file.read()

        # Counting words (sharing text based on distances)
        words = text.split()
        word_count = len(words)

        # Write the result in the output file
        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}")
Sumy.amiri Download Python

Submit answer

Submitting answers is currently unavailable.

×
×
Close