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

2024-05-16 21:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,如果字符串包含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包中调用的,非常简单

^{pr2}$

所以第一个算法需要一个参数,而第二个算法没有。在

根据文本,我们得到变量

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

它作为参数传递给另一个函数

output = func(user_agent, search algorithm)

Tags: 字符串算法mozillasearchos逻辑algorithmlike
1条回答
网友
1楼 · 发布于 2024-05-16 21:40:23

没有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)

相关问题 更多 >