[英]Advanced replace
我有一个包含文本的大文件(2GB),我需要在每一行(每行都是单独的)中替换该行中存在的令牌的所有子字符串(在未定义的位置),并由前缀KEYWORD_ID /标识为令牌和原始词:
例:
This is an example of the KEYWORD_ID/Replace_Command that is given as an input,
replace command should be replaced
输出应如下所示:
This is an example of the KEYWORD_ID/Replace_Command that is given as an input,
KEYWORD_ID/Replace_Command replace command should be replaced
可能连续出现许多KEYWORD_ID
关于如何有效执行此操作的任何想法?
谢谢您的帮助
2GB一点也不大,只是逐行进行迭代,然后使用regex
如果是一个替换命令:
import re
str = 'This is an example of the KEYWORD_ID/Replace_Command that is given as an input, replace command should be replaced'
print(re.sub(r'\breplace\b', re.search('KEYWORD_ID/\w+',str).group(), str))
# returns: This is an example of the KEYWORD_ID/Replace_Command that is given as an input, KEYWORD_ID/Replace_Command command should be replaced
如果更多,您将不得不遍历re.group
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.