python 中的 sed 命令

NEH*_*ARY 1 python

我的输入是

Type combinational  function (A B)
Run Code Online (Sandbox Code Playgroud)

想要输出是

Type combinational 
function (A B)
Run Code Online (Sandbox Code Playgroud)

我使用了代码及其工作原理

sed 's/\([^ ]* [^ ]*\) \(function.*\)/\1\n\2/' Input_file
Run Code Online (Sandbox Code Playgroud)

当我在 python 脚本中使用这段代码时os.systemsubprocess它给了我错误。我怎样才能sed在 python 脚本中执行这个。或者我如何为上面的内容编写Python代码sed code。使用的Python代码

cmd='''
sed 's/\([^ ]* [^ ]*\) \(function.*\)/\1\n\2/' Input_file
'''
subprocess.check_output(cmd, shell=True)
Run Code Online (Sandbox Code Playgroud)

错误是

sed: -e expression #1, char 34: unterminated `s' command 
Run Code Online (Sandbox Code Playgroud)

tri*_*eee 5

字符串\n中的 被 Python 替换为文字换行符。正如 @bereal 在评论中所建议的,您可以通过使用r'''...'''而不是'''...'''围绕脚本来避免这种情况;但更好的解决方案是避免sed使用 Python 本身已经做得很好的事情。

with open('Input_file') as inputfile:
   lines = inputfile.read()
lines = lines.replace(' function', '\nfunction')
Run Code Online (Sandbox Code Playgroud)

这比当前sed脚本稍微宽松一些,因为它不需要在function标记之前正好有两个空格分隔的标记。如果你想严格一点,那就试试re.sub()吧。

import re
# ...
lines = re.sub(r'^(\S+\s+\S+)\s+(function)', r'\1\n\2', lines, re.M)
Run Code Online (Sandbox Code Playgroud)

(切线,你也想避免不必要的shell=True;也许请参阅subprocess 中 'shell=True' 的实际含义