条件字符串插入

时间:2015-02-22 23:52:35

标签: python regex

我们可以写一个Python程序来转

2.4 Threads /35,Black,notBold,notItalic,closed,TopLeftZoom,0,0,0.0
      2.4.1 Multithreading/35,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0
          2.4.4.1 Hierarchical Design 28/39,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0

2.4 Threads 24/35,Black,notBold,notItalic,closed,TopLeftZoom,0,0,0.0
      2.4.1 Multithreading 24/35,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0
          2.4.4.1 Hierarchical Design 28/39,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0

要点是:

  1. 每行都有/,后跟数字和逗号。

  2. 如果/前面没有数字,请在/前添加数字减11。

  3. 如果/前面已有一个数字,那么就单独留下一行。

1 个答案:

答案 0 :(得分:2)

您可以使用RegEx,(\s*\d*)/(\d+)捕获/周围的数字,然后您可以根据您的条件使用自定义函数替换第一个数字,例如

def replacer(matchobj):
    if matchobj.group(1).lstrip() == "":
        return " {}/{}".format(int(matchobj.group(2)) - 11, matchobj.group(2))
    else:
        return "/".join(matchobj.groups())

print(re.sub(r"(\s*\d*)/(\d+)", replacer, data))

<强>输出

2.4 Threads 24/35,Black,notBold,notItalic,closed,TopLeftZoom,0,0,0.0
      2.4.1 Multithreading 24/35,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0
          2.4.4.1 Hierarchical Design 28/39,Black,notBold,notItalic,open,TopLeftZoom,0,0,0.0

RegEx (\s*\d*)/(\d+)表示匹配零个或多个空格后跟零个或多个数字后跟/个字符,然后是一个或多个数字。