How to capitalize some words in a text file?

formatting, python, python-2.7, text-manipulation

Solution

You should split the words, and capitalise only those which are longer than three letters.

`words.txt`:

each word of this sentence is capitalized
some more words
an other line
import string


with open('words.txt') as file:
    # List to store the capitalised lines.
    lines = []
    for line in file:
        # Split words by spaces.
        words = line.split(' ')
        for i, word in enumerate(words):
            if len(word.strip(string.punctuation + string.whitespace)) > 3:
                # Capitalise and replace words longer than 3 (without punctuation).
                words[i] = word.capitalize()
        # Join the capitalised words with spaces.
        lines.append(' '.join(words))
    # Join the capitalised lines.
    capitalised = ''.join(lines)

# Optionally, write the capitalised words back to the file.
with open('words.txt', 'w') as file:
    file.write(capitalised)

Problem

I have a text file which have normal sentences. Actually I was in hurry while typing that file so I just capitalized the first letter of first word of the sentence (as per English grammar). But now I want that it would be better if each word's first letter is capitalized. Something like: Each Word of This Sentence is Capitalized Point to be noted in above sentence is of and is are not capitalized, actually I want to escape the words which has equal to or less than 3 letters. What should I do?

Original source

Related problems