python regex和写文件查询

时间:2018-10-11 01:25:56

标签: python regex

我有一个问题,关于使用正则表达式和循环更改后如何写一个文件。

我想更改“ left”下“ text-align:left;”的“ p.FM_table_cell_body* {”。 (*代表数字)

这是一个css示例文件,如下所示:

file = '''p.FM_table_cell_body1 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:left;
    text-indent:0.000pt;
}

p.FM_table_cell_body2 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:left;
    text-indent:0.000pt;
}

p.FM_table_cell_body3 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:left;
    text-indent:0.000pt;
}'''

这就是我正在尝试的

import re

for A in range(2,4) :  # these numbers are just example, they can be changed.
    print(A)
    with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output_test.css","wt",encoding="utf-8") as file_new :
        new_content = re.sub(r"(p\.FM_table_cell_body" + str(A) + " {[^}]+text-align:)left", r"\1center", file)
        file_new.write(str(new_content))        

但是此代码仅更改“ text-align:center;”下的“ FM_table_cell_body3”。

我想要的输出如下:

file_new = '''p.FM_table_cell_body1 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:left;
    text-indent:0.000pt;
}

p.FM_table_cell_body2 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:center;   # 'left' is changed to 'center'
    text-indent:0.000pt;
}

p.FM_table_cell_body3 {
    margin-left:0.000pt;
    margin-right:0.000pt;
    text-align:center;  # 'left' is changed to 'center'
    text-indent:0.000pt;
}'''

我要修改哪一部分?

谢谢。

1 个答案:

答案 0 :(得分:0)

每次循环时,您只是在编写当前替换项,从而覆盖上一次迭代所做的操作。

您应该在循环中每次更新new_content字符串,然后在末尾写入文件。

import re

new_content = file
for A in range(2,4) :  # these numbers are just example, they can be changed.
    print(A)
    new_content = re.sub(r"(p\.FM_table_cell_body" + str(A) + " {[^}]+text-align:)left", r"\1center", new_content)
with open ("C:\\TEST\\HTML\\Output_sample1\\Responsive HTML5\\Output_test.css","wt",encoding="utf-8") as file_new :
    file_new.write(str(new_content))