【问题标题】:Python 3: How can I get os.getcwd() to play nice with re.sub()?Python 3:如何让 os.getcwd() 与 re.sub() 配合使用?
【发布时间】:2013-01-15 11:26:59
【问题描述】:

我正在尝试使用python 3.3 将文件中的某些内容替换为当前工作目录。我有:

def ReplaceInFile(filename, replaceRegEx, replaceWithRegEx):
    ''' Open a file and use a re.sub to replace content within it in place '''
    with fileinput.input(filename, inplace=True) as f:
        for line in f:
            line = re.sub(replaceRegEx, replaceWithRegEx, line)
            #sys.stdout.write (line)
            print(line, end='')

我就是这样使用它的:

ReplaceInFile(r'Path\To\File.iss', r'(#define RootDir\s+)(.+)', r'\g<1>' + os.getcwd())

不幸的是,我的路径是 C:\Tkbt\Launch,所以我得到的替换是:

#define RootDir C:  kbt\Launch

即它将\t 解释为选项卡。

所以在我看来,我需要告诉 python 双重转义来自 os.getcwd() 的所有内容。我想也许.decode('unicode_escape') 可能是答案,但事实并非如此。谁能帮帮我?

我希望有一个解决方案不是“用'\\' 替换每个'\'”。

【问题讨论】:

  • 它不仅仅是 os.getcwd() - 它是任何路径。 re.escape() 也不起作用,因为它转义了 ':' - C\:\Tkbt\Launch
  • 你不能用/代替\吗?
  • @fp: os.getcwd() 返回带有反斜杠的路径。这与路径文字无关。

标签: python regex python-3.x


【解决方案1】:

恐怕你必须求助于.replace('\\', '\\\\'),这是唯一的选项你必须使这项工作。

  • unicode_escape使用编码然后再从ASCII解码会很好,如果它有效的话:

    replacepattern = r'\g<1>' + os.getcwd().encode('unicode_escape').decode('ascii')
    

    这对路径是正确的:

    >>> print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + r'C:\Path\to\File.iss'.encode('unicode_escape').decode('ascii'), '#define Root
    #define RootDir C:\Path\to\File.iss
    

    但不适用于现有的非 ASCII 字符,因为 re.sub() 不处理 \u\x 转义。

  • 不要使用re.escape() 转义字符串中的特殊字符,这会转义太多:

    >>> print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + re.escape(r'C:\Path\To\File.iss'), '#define RootDir foo/bar/baz'))
    #define RootDir C\:\Path\To\File\.iss
    

    注意那里的\:

只有 .replace() 会产生有效的替换模式,包括非 ASCII 字符:

>>> print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + 'C:\\Path\\To\\File-with-non-
ASCII-\xef.iss'.replace('\\', '\\\\'), '#define Root
#define RootDir C:\Path\To\File-with-non-ASCII-ï.iss

【讨论】:

  • Urgle; re.sub() 承诺解释所有转义码,但 \xab\uabcd 不会被解释。
猜你喜欢
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2022-12-04
相关资源
最近更新 更多