Count the words inside the file
Write a program to read a text file, count the number of words, and write the number of words in a new file.
Write a program to read a text file, count the number of words, and write the number of words in a new file.
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()
# 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}")
Submitting answers is currently unavailable.
برای استفاده از این بخش باید وارد حساب کاربریت بشی
ورود/ثبت نام If you don’t understand the exercise or can’t solve it for any reason, that’s completely
normal—don’t worry 😊
Try checking out easier exercises and reviewing different answers
submitted by others. Gradually, you can move on to more challenging exercises. Also, your answer
might be correct even if it’s different from others.