sfactor
sfactor

Reputation: 13062

how to search for one of a set of strings in python

I need extracted a string from certain column of a data file and perform some algorithms on that string based on what is contained in that string.

So for example, if the string contains iPhone, iPad etc I need to run algorithm 'A' and if it contains Android, Symbian etc I need to run algorithm 'B'.

I have never done python before but I have an existing python script that I need to enter this logic into. How do I make the logic for the IF command to test if the string contains any one these substrings? Do I use some kind of regexp or is there some simple way to do this in python.

These strings are user-agent strings such as

Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5H11 Safari/525.20

Mozilla/5.0 (Linux; U; Android 1.6; en-us; A-LINK PAD ver.1.9.1_1 Build/Donut) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1

The algorithms are called from a installed python package as simple

AlgorithmA(some_other_string)
AlgorithmB()

So the first algorithm takes a argument while the second does not.

Based on the text, we get the variable

search_algorithm = AlgorithmA(some_other_string)
                 or
search_algorithm = AlgorithmB()

and this is passed as argument to another function

output = func(user_agent, search algorithm)

Upvotes: 2

Views: 299

Answers (1)

eumiro
eumiro

Reputation: 213115

You can do it without regexp:

def funcA(text):
   ...

def funcB(text):
   ...

algo = ( ('iPhone', funcA),
         ('Android', funcA),
         ('Symbian', funcA),
         ('Dell', funcB),
         ('Asus', funcB),
         ('HP', funcB) )

text = '... your text ...'

for word, func in algo:
    if word in text:
        func(text)

Upvotes: 4

Related Questions