【问题标题】:How to find digits, pad zeros with regex and replace path in Python?如何在 Python 中查找数字、用正则表达式填充零并替换路径?
【发布时间】:2015-05-17 18:18:07
【问题描述】:

我正在尝试获取目录中所有 .txt 文件的文件路径,并替换每个文件的根目录,并为具有不同填充长度的文件路径填充零。考虑一个文件列表的例子:

./Old directory/ABC 01/XYZ 1 - M 1.txt
./Old directory/ABC 01/XYZ 1 - M 2.txt
./Old directory/ABC 01/XYZ 1 - M 3.txt

现在需要一个 Python 代码来给我这个输出:

./New directory/ABC 00001/XYZ 0001 - M 001.txt
./New directory/ABC 00001/XYZ 0001 - M 002.txt
./New directory/ABC 00001/XYZ 0001 - M 003.txt

可重现的代码(我的努力):

import os
import re
files = []
for root, directories, files in os.walk('./Old directory'):
    files = sorted([f for f in files if os.path.splitext(f)[1] in ('.txt')])
    for file in files:
        files.append(os.path.join(root, file))
for file in files:
    file.replace('./Old directory', './New directory')

【问题讨论】:

  • 那段代码有什么作用?这与您的预期有何不同?到目前为止,它似乎没有做出任何努力来填充数字或实现正则表达式;你的尝试在哪里?
  • 它为我提供了以 .txt 扩展名结尾的文件列表,并替换了根目录。
  • 这就是我卡住的地方。我可以使用 re.findall(r"[-+]?\d*\.\d+|\d+", file) 获取数字,但不知道进一步的步骤。
  • 那么为什么示例中没有包含输入以及预期和实际输出?请阅读stackoverflow.com/help/mcve“我现在该怎么办?” 通常不是一个好的 SO 问题。
  • 字符串在 Python 中是不可变的,这意味着像 str.replace()re.sub() 这样的方法不会更改字符串;相反,它们返回一个您应该分配给变量的新字符串。例如:new_file = file.replace(...).

标签: python regex replace os.path


【解决方案1】:

我怀疑这不是那么容易,但看起来你很接近。

import re
...
for file in files:
    file = file.replace('./Old directory', './New directory')
    p = re.compile(ur'(\d+)')
    file = re.sub(p, u"000$1", file)

View testing example

【讨论】:

    【解决方案2】:

    在您的代码中将同一变量 files 用于两种不同的目的是致命的 - 我将一个实例更改为 filenames,并补充了代码以进行零填充。

    import os
    import re
    filenames = []
    for root, directories, files in os.walk('./Old directory'):
        files = sorted([f for f in files if os.path.splitext(f)[1] in ('.txt')])
        for file in files:
            filenames.append(os.path.join(root, file))
    def padzeros(s, m, g, width):   # pad the group g of match m in string s 
        return s[:m.start(g)]+m.group(g).zfill(width)+s[m.end(g):]
    for file in filenames:
        file = file.replace('./Old directory', './New directory')
        m = re.search(r'\D+(\d+)\D+(\d+)\D+(\d+)', file)
        # important: pad from last to first match
        file = padzeros(file, m, 3, 3)
        file = padzeros(file, m, 2, 4)
        file = padzeros(file, m, 1, 5)
        print file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多