【问题标题】:How to cut part of the text and replace each line with Python and RegEx如何剪切部分文本并用 Python 和 RegEx 替换每一行
【发布时间】:2019-03-27 15:09:31
【问题描述】:

您好,我是 Python 的初学者,刚刚开始学习它并使用 RegEx 进行文本操作。 如果我违反了 StackOverflow 的一些规则,我很抱歉

我正在用 Python 编写一个脚本,我将从第一行获取(剪切)日期和时间,并在每一行替换“日期”“TimeWindowStart”和“TimeWindowEnd”

ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59

Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000

我知道如何使用正则表达式日期进行选择

([0-9][0-9]|2[0-9])/[0-9][0-9](/[0-9][0-9][0-9][0-9])?

以及如何选择时间

([0-9][0-9]|2[0-9]):[0-9][0-9](:[0-9][0-9])?

但我坚持如何选择部分文本复制它然后找到我想用 re.sub 函数替换的文本

所以最终的输出应该是这样的:

ReportDate=, TimeWindowStart=, TimeWindowEnd=

03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000 
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000 
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000 
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000

【问题讨论】:

    标签: python regex


    【解决方案1】:

    首先,您可以在正则表达式查询中指定一个量词,因此如果您需要 4 个数字,则不需要 [0-9][0-9][0-9][0-9],但您可以使用 [0-9]{4}。要捕获表达式,请将其括在圆括号中 value=([0-9]{4}) 只会给您数字

    如果你想使用re.sub,你只需要给它一个模式,一个替换字符串和你的输入字符串,例如re.sub(pattern, replacement, string)

    因此:

    import re
    
    txt = """ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
    
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
    """
    
    pattern_date = 'ReportDate=([0-9]{2}/[0-9]{2}/[0-9]{4})'
    report_date = re.findall(pattern_date, txt)[0]
    
    pattern_time_start = 'TimeWindowStart=([0-9]{2}:[0-9]{2}:[0-9]{2})'
    start_time = re.findall(pattern_time_start, txt)[0]
    
    pattern_time_end = 'TimeWindowEnd=([0-9]{2}:[0-9]{2}:[0-9]{2})'
    end_time = re.findall(pattern_time_end, txt)[0]
    
    splitted = txt.split('\n')  # Split the txt so that we skip the first line
    
    txt2 = '\n'.join(splitted[1:])  # text to perform the sub 
    
    # substitution of your values
    txt2 = re.sub('Date', report_date, txt2)
    txt2 = re.sub('TimeWindowStart', start_time, txt2)
    txt2 = re.sub('TimeWindowEnd', end_time, txt2)
    
    txt_final = splitted[0] + '\n' + txt2
    print(txt_final)
    

    输出:

    ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
    
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
    

    【讨论】:

    • 谢谢@dzang,这对我帮助很大!
    • @krcha 很高兴听到这个消息。祝你任务顺利!如果您对给出的答案之一感到满意,最好将其标记为已接受的答案。欢呼
    【解决方案2】:

    这是一个部分答案,因为我不太了解用于处理文本文件的 Python API。您可以阅读文件的第一行,并提取报告日期和开始/结束窗口时间的值。

    first = "ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59"
    ReportDate = re.sub(r'ReportDate=([^,]+),.*', '\\1', first)
    TimeWindowStart = re.sub(r'.*TimeWindowStart=([^,]+),.*', '\\1', first)
    TimeWindowEnd = re.sub(r'.*TimeWindowEnd=(.*)', '\\1', first)
    

    写出第一行,去掉三个变量的值。

    然后,您需要做的就是在随后的每一行中读取并执行以下替换:

    line = "Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000"
    line = re.sub(r'\bDate\b', ReportDate, line)
    line = re.sub(r'\b TimeWindowStart\b', TimeWindowStart, line)
    line = re.sub(r'\ TimeWindowEnd\b', TimeWindowEnd, line)
    

    这样处理完每一行,就可以写入输出文件了。

    【讨论】:

      【解决方案3】:

      这是我的代码:

      import re
      
      s = """ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
      
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
      Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000"""
      
      datereg = r'(\d{2}/\d{2}/\d{4})'
      timereg = r'(\d{2}:\d{2}:\d{2})'
      
      dates = re.findall(datereg, s)
      times = re.findall(timereg, s)
      
      # replacing one thing at a time
      result = re.sub(r'\bDate\b', dates[0],
                  re.sub(r'\bTimeWindowEnd\b,', times[1] + ',',
                      re.sub(r'\bTimeWindowStart\b,', times[0] + ',',
                          re.sub(timereg, '', 
                              re.sub(datereg, '', s)))))
      
      print(result)
      

      输出:

      ReportDate=, TimeWindowStart=, TimeWindowEnd=
      
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
      

      【讨论】:

        【解决方案4】:

        试试这个,

        import re
        
        #Open file and read line by line
        with open("a") as file:
         # Get and process first line
         first_line = file.readline()
         m = re.search("ReportDate=(?P<ReportDate>[0-9/]+), TimeWindowStart=(?P<TimeWindowStart>[0-9:]+), TimeWindowEnd=(?P<TimeWindowEnd>[0-9:]+)",first_line)
         first_line= re.sub(m.group('ReportDate'), "", first_line)
         first_line= re.sub(m.group('TimeWindowStart'), "", first_line)
         first_line= re.sub(m.group('TimeWindowEnd'), "", first_line)
         print(first_line)
        
         # Process rest of the lines
         for line in file:
            line = re.sub(r'\bDate\b', m.group('ReportDate'), line)
            line = re.sub(r'\bTimeWindowStart\b', m.group('TimeWindowStart'), line)
            line = re.sub(r'\bTimeWindowEnd\b', m.group('TimeWindowEnd'), line)
            print(line.rstrip())
        

        输出:

        ReportDate=, TimeWindowStart=, TimeWindowEnd=
        
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
        

        【讨论】:

          【解决方案5】:

          找到如下所示的明确解决方案:

          import re
          
          input_str = """
          ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
          """
          
          # Divide input string into two parts: header, body
          header = input_str.split('\n')[1]
          body = '\n'.join(input_str.split('\n')[2:])
          
          # Find elements to be replaced
          ri = re.findall('\d{2}/\d{2}/\d{4}',header)
          ri.extend(re.findall('\d{2}:\d{2}:\d{2}',header))
          
          # Replace elements
          new_header = header.replace(ri[0],'')\
                             .replace(ri[1],'')\
                             .replace(ri[2],'')
          
          new_body = body.replace('Date',ri[0])\
                         .replace('TimeWindowStart',ri[1])\
                         .replace('TimeWindowEnd',ri[2])
          
          # Construct the result string
          full_string = new_header + '\n\n' + new_body
          

          只需找到要替换为正则表达式的项目并执行普通字符串替换即可。我认为它是有效的,直到你只有很少的元素。

          【讨论】:

            猜你喜欢
            • 2018-12-26
            • 2015-04-17
            • 2015-07-21
            • 2014-03-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-02-16
            • 2015-11-22
            相关资源
            最近更新 更多