Python中文
首页
教程
问答
标签
搜索
登录
注册
用于搜索和替换大字符串的最快Python方法
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我正在寻找最快的方法来替换一个非常大的字符串中的大量子字符串。这里有两个我用过的例子。</p> <p>findall()感觉更简单、更优雅,但它需要惊人的时间。</p> <p>finditer()会遍历一个大文件,但我不确定这样做是否正确。</p> <p>这是一些示例代码。注意,我感兴趣的实际文本是一个大小约为10MB的字符串,这两种方法有很大的不同。</p> <pre><code>import re def findall_replace(text, reg, rep): for match in reg.findall(text): output = text.replace(match, rep) return output def finditer_replace(text, reg, rep): cursor_pos = 0 output = '' for match in reg.finditer(text): output += "".join([text[cursor_pos:match.start(1)], rep]) cursor_pos = match.end(1) output += "".join([text[cursor_pos:]]) return output reg = re.compile(r'(dog)') rep = 'cat' text = 'dog cat dog cat dog cat' finditer_replace(text, reg, rep) findall_replace(text, reg, rep) </code></pre> <p><strong>更新</strong>将re.sub方法添加到测试:</p> <pre><code>def sub_replace(reg, rep, text): output = re.sub(reg, rep, text) return output </code></pre> <p><strong>结果</strong></p> <p>回复:sub()-0:00:00.031000<br/> finditer()-0:00:00.109000<br/> 芬达尔()-0:01:17.260000</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>标准方法是使用内置的</p> <pre><code>re.sub(reg, rep, text) </code></pre> <p>顺便说一下,两个版本之间性能差异的原因是,第一个版本中的每个替换都会导致重新复制整个字符串。拷贝很快,但是当你一次拷贝10 MB时,足够的拷贝会变慢。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
python语法错误(如果不在Z中,则在X中表示s)
5 回答
Python语法错误(无效)概率
6 回答
python语法错误*带有可选参数的args
9 回答
python语法错误2.5版有什么办法解决吗?
2 回答
Python语法错误2.7.4
4 回答
python语法错误30/09/2013
10 回答
Python语法错误E001
9 回答
Python语法错误not()op
1 回答
python语法错误outpu
6 回答
Python语法错误print len()
3 回答
python语法错误w3
9 回答
Python语法错误不是caugh
8 回答
python语法错误及yt-packag的使用
2 回答
python语法错误可以查出来!!瓦里亚布
9 回答
Python语法错误可能是缩进?
2 回答
Python语法错误和缩进
8 回答
Python语法错误在while循环中生成随机numb
8 回答
Python语法错误在哪里?
8 回答
python语法错误在尝试导入包时,但仅在远程运行时
2 回答
Python语法错误在电子邮件地址提取脚本中
9 回答