如何在python中搜索一组字符串之一

时间:2011-01-12 10:37:02

标签: python regex string

我需要从数据文件的某一列中提取一个字符串,并根据该字符串中包含的内容对该字符串执行一些算法。

例如,如果字符串包含 iPhone,iPad等,我需要运行算法'A',如果它包含Android,Symbian等,我需要运行算法'B'。

我之前从未做过python但是我有一个现有的python脚本需要输入这个逻辑。如何使IF命令的逻辑测试字符串是否包含任何一个这些子字符串?我是否使用某种regexp或者有一些简单的方法在python中执行此操作。

这些字符串是用户代理字符串,例如

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

从已安装的python包调用算法简单

AlgorithmA(some_other_string)
AlgorithmB()

所以第一个算法接受一个参数,而第二个算法没有。

根据文字,我们得到变量

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

并将其作为参数传递给另一个函数

output = func(user_agent, search algorithm)

1 个答案:

答案 0 :(得分:4)

你可以在没有正则表达式的情况下完成:

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)