mervinmemory

mervinmemory

V2EX 第 186658 号会员,加入于 2016-08-12 14:02:50 +08:00
mervinmemory 最近回复了
为大佬点赞。
来自 gpt 的回复:


对于每次来的新字符串都要遍历整个正则表达式数组,这可能导致性能下降。如果你希望提高匹配速度,可以考虑使用更高效的数据结构,如字典( Dictionary )或者前缀树( Trie )。

下面是一种可能的优化方法:

1. 使用字典替代列表:将正则表达式和相应的操作存储在字典中,其中键为正则表达式字符串,值为对应的操作。这样可以通过正则表达式快速查找到对应的操作,而无需遍历整个列表。

2. 在字典中使用前缀树:将正则表达式作为前缀树的键,操作作为对应节点的值。前缀树可以提高匹配效率,特别是当正则表达式存在共同前缀时,可以减少不必要的匹配操作。

这是一个示例代码,展示了如何使用字典和前缀树进行优化:

```python
import re
from collections import defaultdict

class TrieNode:
def __init__(self):
self.children = defaultdict(TrieNode)
self.operations = []

def insert(root, regex, operation):
node = root
for char in regex:
node = node.children[char]
node.operations.append(operation)

def find_operations(root, text):
results = []
node = root
for char in text:
if char in node.children:
node = node.children[char]
results.extend(node.operations)
elif '*' in node.children:
node = node.children['*']
results.extend(node.operations)
else:
node = root
return results

# 构建前缀树
root = TrieNode()
for regex, operation in _list:
insert(root, regex.pattern, operation)

# 搜索匹配操作
text = "待匹配的字符串"
matching_operations = find_operations(root, text)

# 对匹配操作进行处理
for operation in matching_operations:
# 处理匹配操作
```

注意,这只是一种优化思路,并且需要根据你的具体需求进行适当的调整。如果正则表达式的数量非常庞大,可能需要使用更高级的算法和数据结构来进一步提高性能。
求个码大哥,谢谢!
bWVydmluLm1lbW9yeUBnbWFpbC5jb20=
2022-02-08 16:55:29 +08:00
回复了 forsky 创建的主题 问与答 马上过生日了,有啥礼物送的吗?
@forsky 找了两个妹子,三个人折腾了一晚上。。。但愿是我理解的那样
2022-02-08 16:54:11 +08:00
回复了 niceyuri 创建的主题 北京 最近过年洗浴去了,推开了新世界的大门
哪家呀?
2021-05-17 16:47:36 +08:00
回复了 AllenHua 创建的主题 硬件 2021 年 5 月 预算 9000 买 windows 笔记本还是 nuc,求推荐
nuc 固定点办公码代码挺香的,笔记本适合出差。。。我现在板砖工具就是 nuc
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3251 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 16ms · UTC 12:12 · PVG 20:12 · LAX 05:12 · JFK 08:12
Developed with CodeLauncher
♥ Do have faith in what you're doing.