开发者

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

开发者 https://www.devze.com 2023-02-04 07:26 出处:网络
I need extracted a string from certain column of a data file and perform some algorithms on that string bas开发者_开发知识库ed on what is contained in that string.

I need extracted a string from certain column of a data file and perform some algorithms on that string bas开发者_开发知识库ed 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)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消