Python Programming - Finding Specific Word Variations in Text File (initial Caps and Lowercase)

391

4

Posted

Introduction: Python Programming - Finding Specific Word Variations in Text File (initial Caps and Lowercase)

Python program to find variations of a specific word, for example, one version of the word with the initial letter capitalized and a 2nd version with all the letters lowercase. This program is counting the number of times "Thou" and "thou" appears in the complete works of Shakespeare. Below and attached. Complete works of Shakespeare is attached in a text file as well.

# ThouCount.py
print ("This program will count the number of 'Thou' and 'thou' in ")
print ("the works of Shakespeare.")
thefile = open("Shakespeare.txt")
ThouCount = 0

# for each line in the file
for line in thefile:
    # split the line into words
    splitline = line.split()
    # check to see if word is "Thou" or "thou"
    for word in splitline:
        if word == ("thou"):
            print("Instance of lowercase thou found!")
            ThouCount = ThouCount + 1
            print ("Count is:", ThouCount)
        elif word == ("Thou"):
            print ("Instance of Thou with capital 'T' found")
            ThouCount = ThouCount + 1
            print ("Count is:", ThouCount)
            
print ("The total count of 'Thou' and 'thou' in all of Shakespeare's works is:", ThouCount)

Share

    Recommendations

    • Science of Cooking

      Science of Cooking
    • Pocket-Sized Contest

      Pocket-Sized Contest
    • Spotless Contest

      Spotless Contest
    user

    We have a be nice policy.
    Please be positive and constructive.

    Tips

    Questions

    Comments