0% found this document useful (0 votes)
5 views

Program to count number of lines etc

The document describes a Python function that analyzes a text file for various metrics including the number of lines, words, characters, vowels, and numbers. It also counts the occurrences of each word and identifies repeated words. The function is demonstrated with a sample file, producing specific output metrics.

Uploaded by

pramikarani87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Program to count number of lines etc

The document describes a Python function that analyzes a text file for various metrics including the number of lines, words, characters, vowels, and numbers. It also counts the occurrences of each word and identifies repeated words. The function is demonstrated with a sample file, producing specific output metrics.

Uploaded by

pramikarani87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Counting from File using Functions:

def analyze_file(file_path):
vowels = "aeiouAEIOU"
num_lines = num_words = num_chars = num_vowels = num_numbers = 0
word_counts = {}

with open(file_path, 'r') as file:


for line in file:
num_lines += 1 # Count lines
num_chars += len(line) # Count characters (including spaces)
words = line.split() # Split line into words
num_words += len(words) # Count words
num_vowels += sum(1 for char in line if char in vowels) # Count vowels
num_numbers += sum(1 for char in line if char.isdigit()) # Count numbers

# Update word counts


for word in words:
# Normalize the word to lowercase and strip punctuation
word = ''.join(char for char in word if char.isalnum()).lower()
if word: # Avoid empty strings
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1

# Identify repeated words


repeated_words = {word: count for word, count in word_counts.items() if count > 1}
# Print results
print(f"Lines: {num_lines}")
print(f"Words: {num_words}")
print(f"Characters: {num_chars}")
print(f"Vowels: {num_vowels}")
print(f"Numbers: {num_numbers}")
print("Repeated Words:")
for word, count in repeated_words.items():
print(f" {word}: {count} times")

# MainCode Line
file_path = "file1.txt" # Replace with your file path
analyze_file(file_path) # Function Call

Content in File : file1.txt


Welcome to the world of programming
Today is the day
Today is a good day
I have 10 chocolates

Output :
Lines: 4
Words: 19
Characters: 93
Vowels: 29
Numbers: 2
Repeated Words:
the: 2 times today: 2 times is: 2 times day: 2 times

You might also like