gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:06:41 25 4
gpt4 key购买 nike

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

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

我以前从未用过 python,但我有一个现有的 python 脚本,我需要将此逻辑输入到其中。如何为 IF 命令创建逻辑以测试字符串是否包含这些子字符串?我是使用某种正则表达式还是在 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)

最佳答案

不用正则表达式也可以:

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)

关于python - 如何在python中搜索一组字符串中的一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4667787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com