Finding honorific text and then capital letters in Python

Viewed 144
file = open('AllCongress.txt', "r")
lines = file.readlines()
file.close()
a = ""
b = ""
c = ""
d = ""
e = ""
f = ""
g = ""
y = ""
z = ""
for x in lines:
    if ((x == "M") or (a == "M")):
        a == "M"
        if((x == "r") or (b == "r")):
            b == "r"
            if((x == ".") or (c == ".")):
                c == "."
                if((x == " ") or (d == " ")):
                    d == " "
                    if((x == x.isupper()) or (e == "A"):
                        e == "A"
                        if((x == x.isupper()) and ((e == "A") and (f == "A"))):
                            f == "A"
                            
                            if((x == x.isupper()) or (g == g.isupper())):
                                g == "A"

I'm trying to divide sections of a .txt file into two separate files based on whether it contains a male or female speaker. Speakers in this file type have their last name in all caps after the honorific. So the male honorific format for speakers in this file is "Mr. XYZ" with XYZ being any 3+ capital letters (3 capital letters in a row is enough to detect anybody in the file as a speaker). The female format is similar, just either "Ms. XYZ" or "Mrs. XYZ".

I want to get all of the text after a speaker name like that is listed and then sort them into separate male and female text file, until the next speaker speaks where I have to determine gender again to sort.

Unfortunately though, I'm new to Python and I'm unable to figure out a way that I can check for both "Mr. " or "Mrs. " and then at least 3 capital letters in a row afterwards. I really just need a way to detect this and I can probably figure out the rest. The code above is this really messy and unfinished way I tried to capture the "Mr. XYZ" part of text.

2 Answers

here is some code (if you have questions -> ask):

with open('yourfile.txt') as file:
    lines = file.read()

lines = lines.split(' ')
for index, word in enumerate(lines):
    if word == 'Mr.' and lines[index + 1].isupper():
        prefix = 'Mr. '
        name = lines[index + 1]
        print(prefix + name)
    elif word == 'Mrs.' and lines[index + 1].isupper():
        prefix = 'Mrs. '
        name = lines[index + 1]
        print(prefix + name)

I suggest you use with statement for opening files. Basically you loop over each word and check if it eaquals what you need.

Use String functions like startswith() or endswith() And don't close the file before reading lines

file = open('AllCongress.txt', "r")
lines = file.readlines()
lines = lines.split(' ')
for x in lines:
 if(x.startswith("Mr."):
  *code here*
 elif(x.startswith("Ms."):
  *code here*
Related