python - Python 的 regex 和 find() 搜索字符串哪个更快?

标签 python xml string-matching

我有一个 XML 字符串

<tags>
   <person1>dave jones</person1>
   <person2>ron matthews</person2>
   <person3>sally van heerden</person3>
   <place>tygervalley</place>
   <ocassion>shopping</ocassion>
</tags>

我想使用“Sally Van Heerden”或“Tygervalley”等搜索词来搜索此 xml 字符串

使用正则表达式查找该字符串中的术语更快,还是 Python 的 find() 方法足够快?我还可以使用 python 的元素树 XML 解析器进行搜索,然后构建 XML 树,然后搜索它,但我担心它会太慢。

以上三个中哪个最快? 还有其他建议吗?

请记住,可以输入多个搜索词,并且还会搜索多个(数千个)XML 字符串。

更新:如何将 xml 字符串拆分为一个列表,删除所有特殊字符,然后将列表转换为一组以及一组搜索词。然后求两个集合的交集?这样会很快吗?

最佳答案

老实说,我认为您必须有一些非常极端的速度要求,这才会成为您的瓶颈,但即使您这样做,对此做出明智决定的唯一方法就是通过测试

首先,使用 find/re.findall 搜索字符串中的一个字符串。不过,我怀疑这是否代表您的用例,您需要确定将运行哪些查询并测试这些查询。

% python -mtimeit "'<tags> <person1>dave jones</person1> <person2>ron matthews</person2> <person3>sally van heerden</person3> <place>tygervalley</place> <ocassion>shopping</ocassion> </tags>'.find('tygervalley')"
1000000 loops, best of 3: 0.279 usec per loop

% python -mtimeit "import re; re.findall('tygervalley', '<tags> <person1>dave jones</person1> <person2>ron matthews</person2> <person3>sally van heerden</person3> <place>tygervalley</place> <ocassion>shopping</ocassion> </tags>')"
100000 loops, best of 3: 2.65 usec per loop

正如我所说,很难想象这种差异是程序中最重要的瓶颈。

关于python - Python 的 regex 和 find() 搜索字符串哪个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10643452/

相关文章:

python - Django/Python 干 : how to avoid repeat code when working with Q objects and model attributes

python - 创建具有长多重索引的 pandas 数据透视表

python - 为什么我使用 pandas 和 xlsxwriter 时会出现值错误?

xml - 如何在未安装 Excel 的情况下将 DBGrid 导出为 OOXML 格式(Excel 2007/2010 格式)?

c++ - xerces-c : Xml parsing multiple files

regex - 正则表达式是编程必须的吗?

SQLite:在启用 FTS4 的表中使用比较运算符进行查询

python - mongoengine - 动态生成 Q()

c# - XDocument.Save() 无法访问文件

machine-learning - 使用循环神经网络进行字符串匹配