emacs样式,基于点的字符串搜索替换python库
eep的Python项目详细描述
emacs风格,基于点的搜索替换python。
它通过在文本中移动point和mark来工作, 有点类似于emacs处理其buffers的方式。这就变成 对于一些需要 文本中在之后使用,在之前使用。
一个例子问题是 here。使用 eep,等价的python代码是
importeeptext="""<p class='q'>Q: Why</p>\n<p class='a'>Because</p>\n <p class='a'>You need to do</p>\n\n <p class='q'>Q: How</p>\n <p class='a'>Do this</p>\n <p class='a'>And that</p>"""es=eep.Searcher(text)print("Before : \n"+str(es)+"\n\n")whilees.search_forward("<p class='q'>"):es.search_forward("<p class='a'>")es.swap_markers()es.insert("<div class='a'>\n")ifes.search_forward("<p class='q'>"):es.search_backward("</p>")es.swap_markers()es.insert("\n</div>")es.goto("end")es.search_backward("<p class='a'>")es.search_forward("</p>")es.insert("\n</div>")es.goto("start")whilees.search_forward("<p class='a'>"):es.replace("<p>")es.goto("start")whilees.search_forward("<p class='q'>Q: "):es.replace("<p class='q'>")print("After : \n"+str(es))
Before : <p class='q'>Q: Why</p> <p class='a'>Because</p> <p class='a'>You need to do</p> <p class='q'>Q: How</p> <p class='a'>Do this</p> <p class='a'>And that</p> After : <p class='q'>Why</p> <div class='a'> <p>Because</p> <p>You need to do</p> </div> <p class='q'>How</p> <div class='a'> <p>Do this</p> <p>And that</p> </div>
用法
- 使用pip install eep 安装
- 实例化搜索器
importeepes=eep.Searcher("this is a sample text. this is a sentence.")
- 搜索者有两个用于定义区域的标记。apoint移动 在搜索、替换、插入等过程中,它是当前的 进行操作的位置。
- mark在成功向前或向后搜索后移动以标记 将区域与point匹配。
# Search forward for first match from current point# Return true if match found# Set mark in beginning and point at endes.search_forward("th")# Search backward for first match from current point# Return true if match found# Set point in beginning and mark at endes.search_backward("th")# Replace marked regiones.replace("dodo")# Insert at current pointes.insert("dodo")# Move the pointes.jump(-3)es.goto(34)# also accepts "start" and "end" strings# Exchange markerses.swap_markers()