【问题标题】:Python - how to add a new line every time there is a pattern is found in a string?Python - 每次在字符串中找到模式时如何添加新行?
【发布时间】:2018-11-23 10:33:10
【问题描述】:

每次在字符串中找到正则表达式列表的模式时,如何添加新行?

我正在使用 python 3.6。

我收到以下输入:

12.13.14 这里应该开始新的一行。

12.13.15 这里应该开始新的一行。

这里有一些文字。它写在一行中。 12.13。这里还有一些文字。 2.12.14。这里还有更多文字。

我希望得到以下输出:

12.13.14

这里应该开始新的一行。

12.13.15

这里应该开始新的一行。

这里有一些文字。它写在一行中。

12.13。

这里还有一些文字。

2.12.14。

这里还有更多文字。

我的第一次尝试返回与输入相同的输出:

in_file2 = 'work1-T1.txt'
out_file2 = 'work2-T1.txt'


start_rx = re.compile('|'.join(
    ['\d\d\.\d\d\.', '\d\.\d\d\.\d\d','\d\d\.\d\d\.\d\d']))


with open(in_file2,'r', encoding='utf-8') as fin2, open(out_file2, 'w', encoding='utf-8') as fout2:
    text_list = fin2.read().split()
    fin2.seek(0)

    for string in fin2:
        if re.match(start_rx, string):
            string = str.replace(start_rx, '\n\n' + start_rx + '\n')

        fout2.write(string)

我的第二次尝试返回错误'TypeError: unsupported operand type(s) for +: '_sre.SRE_Pattern' and 'str''

in_file2 = 'work1-T1.txt'
out_file2 = 'work2-T1.txt'


start_rx = re.compile('|'.join(
            ['\d\d\.\d\d\.', '\d\.\d\d\.\d\d','\d\d\.\d\d\.\d\d']))

with open(in_file2,"r") as fin2, open(out_file2, 'w') as fout3:
    for line in fin2:
        start = False
        if re.match(start_rx, line):
            start = True
        if start == False:
            print ('do something')
        if start == True:
            line = '\n' + line ## leerzeichen vor Pos Nr
            line = line.replace(start_rx, start_rx + '\n')
        fout3.write(line)

【问题讨论】:

  • 请注意,您正在尝试将str.replace 方法与正则表达式一起使用,但它不接受正则表达式。你需要re.sub。尝试text = fin2.read(),然后也尝试fout2.write(re.sub(r'\s*(\d+(?:\.\d+)+\.?)\s*', r'\n\n\1\n', text))。见this demo
  • 这解决了问题。谢谢。

标签: regex python-3.x replace


【解决方案1】:

首先,要使用正则表达式进行搜索和替换,您需要使用re.sub,而不是str.replace

其次,如果您使用re.sub,则不能在替换模式中使用正则表达式模式,您需要将要保留的正则表达式部分分组并在替换中使用反向引用(或者,如果您只想引用整个匹配,使用\g<0>反向引用,不需要捕获组。

第三,当你建立一个未锚定的交替模式时,确保首先出现更长的替代方案,即start_rx = re.compile('|'.join(['\d\d\.\d\d\.\d\d', '\d\.\d\d\.\d\d', '\d\d\.\d\d\.']))。但是,您可以在此处手动使用更精确的模式。

以下是修复代码的方法:

with open(in_file2,'r', encoding='utf-8') as fin2, open(out_file2, 'w', encoding='utf-8') as fout2:
    text = fin2.read()
    fout2.write(re.sub(r'\s*(\d+(?:\.\d+)+\.?)\s*', r'\n\n\1\n', text))

Python demo

模式是

\s*(\d+(?:\.\d+)+\.?)\s*

regex demo

详情

  • \s* - 0+ 个空格
  • (\d+(?:\.\d+)+\.?) - 第 1 组(替换模式中的\1):
    • \d+ - 1 位以上
    • (?:\.\d+)+ - . 和 1+ 位重复 1 次或多次
    • \.? - 可选.
  • \s* - 0+ 个空格

【讨论】:

    【解决方案2】:

    试试这个

    out_file2=re.sub(r'(\d+) ', r'\1\n', in_file2)
    out_file2=re.sub(r'(\w+)\.', r'\1\.\n', in_file2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      相关资源
      最近更新 更多