0

I'm very new to Python. I want to look through an array of strings, and if certain words are matched, return those words as a variable. I want to be able to print the variable outside of that if statement, in the global scope.

fullsubject = cells[2].text.encode("utf-8").replace(",","")
subs = fullsubject.split(' ')
# the above two lines work fine.

Here are some examples of the subs array (where I want to find the words):

subs = ['BX', '4', 'train', 'mechanical', 'problems']
subs = ['UPDATED:', 'MANH', '45', '6', 'trains', 'switch', 'trouble']
subs = ['MANH', '45', '6', 'trains', 'switch', 'trouble']
subs = ['Updated:', 'Queens', 'B62', 'bus', 'OEM', 'Drill']
subs = ['Huntington', 'Branch']

If the array contains "MANH" or "Manhattan", I want the variable borough to equal "MANH".
If the array contains "QNS" or "Queens", I want borough to equal "QNS".
If the array contains "BX" or "Bronx", I want borough to equal "BX".

First I tried it like this:

global borough
for item in subs:
    if item == "BX":
        borough = "BX"
    elif item == "QNS":
        borough = "QNS"
    else:
        borough = "something else"
print borough

but it always prints the last option, "something else".
So then I thought maybe I could do it like this:

borough = []
if [item for item in subs if item=="BX" or "Bronx"]:
    borough.append("BX")
elif [item for item in subs if item=="QNS" or "Queens"]:
    borough.append("QNS")
elif [item for item in subs if item=="MANH"]:
    borough.append("MANH")
elif [item for item in subs if item=="BKLYN" or "Brooklyn"]:
    borough.append("BKLYN")
elif [item for item in subs if item=="STATEN" or "SI"]:
    borough.append("SI")
print borough

But again, I keep getting the last option.

I've searched Stack Overflow, but I can't find the right answer(s). Help?

sprucegoose
  • 486
  • 9
  • 25

1 Answers1

0

You just need to check if your words are in the list. There is not need for the list in the comparison to check if something is true. Then return the variable.

def word_check(string_list):
    for word in string_list:
        if word == "BX" or word == "Bronx":
            borough = "BX"
        elif word == "QNS" or word == "Queens":
            borough = "QNS"
        elif word == "MANH":
            borough = "MANH"
        else:
            borough = "something else"
    return borough

Then you call it like this:

string_list = ['list', 'of', 'words', 'MANH']
borough = word_check(string_list)