首页 > 解决方案 > 使用带引号的字符串的 json.dumps 在 Python 中的 sed 命令不保留单引号

问题描述

对不起,如果标题有点复杂......一个例子会更好地说明我的意思:

我有一个名为 foo 的文本文件,其中包含字符串“bar”。

在 Python 中,我有一本字典:

d = {"key": "item['id']"}

我想用我的字典的 json 转储替换文件中的字符串 bar。命令:

import subprocess
subprocess.call("sed 's#bar#%s#g' foo > foo2" % json.dumps(d),shell=True)

当我 cat 文件 foo2 时,结果是:

> cat foo2
{"key": "item[id]"}

问题是:单引号在 id 周围丢失。我怎样才能避免这种情况?

标签: pythonjsonsedescapingsingle-quotes

解决方案


正如@Shawn 所建议的那样,我使用基于 re.sub 的“python sed”函数在 Python 中完成了这一切:

def psed(foo,bar,source,dest):
    """
    implements a python sed, substituting (with multi-line mode) foo for bar 
    in file source, writing the result in file dest
    """
    with open(source,'r') as f:
        content = f.read()
    f.close()
    content_new = re.sub(foo,bar,content,flags=re.M)

    with open(dest,'w') as f:
        f.write(content_new)
    f.close()

推荐阅读