I have a file of sentences similar to this:

Tom ate his Apple.
Frank shoveled Snow.
Henry drove a Truck.

I would like to prosess each sentence so it only retains the capital letter in the first word, every other word in the senetnce should be lower case. The result would look like this:

Tom ate his apple.
Frank shoveled snow.
Henry drove a truck.

Recommended Answers

All 3 Replies

Member Avatar for Mouche

so pull in the lines:

f = open("sentences.txt","r")
lines = f.readlines()
f.close()

Then sort through each line and uppercase each first letter and lowercase the rest; stick those new sentences into a new list:

lines_new = []

for line in lines:
    lines_new.append(line[0].upper() + line[1:].lower())
commented: Great help +1

Wow LaMouche, this is sweet Python code. I learned a lot about file reading/writing too. Here is what I have, showing it with my test file:

"""
file sentences.txt looks like that:
Tom ate his Apple.
Frank shoveled Snow.
Henry drove a Truck.
"""
f_in = open("sentences.txt","r")
lines = f_in.readlines()
f_in.close()
lines_new = []
for line in lines:
    lines_new.append(line[0].upper() + line[1:].lower())
f_out = open("sentences_fixed.txt", "w")
for line in lines_new:
    f_out.write(line)
f_out.close()
"""
file sentences_fixed.txt looks like that:
Tom ate his apple.
Frank shoveled snow.
Henry drove a truck.
"""

My actual sentence file works fine too. I think I understand your code. Each line is a sentence and line[0].upper() simply makes certain that the first letter in the sentence is capitalized. To this you concatenate with the + the remainder of the sentence converted to lower case. Nice example of string slicing!

Thanks!

Member Avatar for Mouche

You got it. I'm glad it works for you. I always like to be a good help to people despite my lack of experience.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.