Python:re.sub 和 os.path.abspath

Python: re.sub with os.path.abspath

我在文件中有一行: 'some text /some/path' 其中路径可以是相对的或绝对的。我想用绝对路径替换它。 我试过这个:

re.sub('some text (.*)','some text {}'.format(os.path.abspath(r'')),line)

但是,匹配的字符串被视为没有任何路径的文件名,结果字符串是 /path/to/the/file//some/path

基本上,相对路径和绝对路径都是'path/to/the/file/'+'matched_string'。 如果我在 re.sub 之外使用 os.path.abspath,它会给出正确的路径。

我该如何解决这个问题?

谢谢, 伊万

如果您将一个函数作为替换传递给 re.sub,该函数将以匹配对象作为参数被调用:

#!/usr/bin/env python

import os, re

os.chdir('/tmp/')
line='some text .'

print(re.sub('some text (.*)',
             lambda match: 'some text {}'.format(os.path.abspath(match.group(1))),
             line))

...正确地作为输出发出(在 MacOS 上,其中 /tmp 是指向 /private/tmp 的符号链接):

some text /private/tmp