正则表达式处理文本问题

时间:2015-01-20 11:10:39

标签: regex

我有以下文字示例:

Sample Supplier 123

 AP Invoices    123456  -229.00
 AP Invoices    235435  337.00  
 AP Invoices    444323  228.00  
 AP Invoices    576432  248.00  

它来自一个包含21,000行的文本文件,其中列出了针对供应商的发票。

每个供应商的发票块上的模式始终相同,其中:

  1. 供应商名称从行首开始
  2. 发票将从供应商名称下方列出2行,缩进一个空格。
  3. 我想知道我是否可以使用正则表达式(我在Windows PC上使用TextPad作为文本编辑器)来:

    1. 使用标签(\ t)
    2. 附加每个发票行
    3. 将供应商名称添加到选项卡前面,以便每个发票行现在以供应商名称开头,以及一个选项卡,其中供应商名称取自每个发票块开头上方的2行
    4. 从发票清单上方删除供应商名称行。
    5. 预期产出:

      Sample Supplier 123  AP Invoices    123456  -229.00
      Sample Supplier 123  AP Invoices    235435  337.00  
      Sample Supplier 123  AP Invoices    444323  228.00  
      Sample Supplier 123  AP Invoices    576432  248.00  
      

      我意识到我可能在这里要求“月亮在棍子上”,但另一种方法是通过一个21,000行文本文件并将数据复制并粘贴到Excel中,这可能不是很好用我的时间。

      也许我不能用一个简单的正则表达式来做,或者根本不可能。

      非常感谢任何建议。

      由于

2 个答案:

答案 0 :(得分:0)

我会用一个简单的Python脚本来解决这个问题:

currentheader = ""
with open("yourfile.txt") as f:
    with open("newfile.txt","w") as fw:
        for line in f:
            if len(line.strip()) == 0:
                continue
            elif line[0] != " ": #new header
                currentheader = line[:-1]
            else:
                fw.write(currentheader + "\t" + line[1:])

要使其正常工作,在Windows上您必须install Python。 Python 2或3都应该与此脚本一起使用。安装Python后,打开命令行(Win+RcmdEnter),如有必要,使用cd foldername导航到文件所在的文件夹,然后键入python dealWithTextIssue.py(在将脚本保存为“dealWithTextIssue.py”之后。

答案 1 :(得分:0)

我认为只有正则表达式才能解决这个问题,你必须做一些编程。我在PHP中制作了一个小脚本:

$string = <<<EOL
Sample Supplier 123

 AP Invoices    123456  -229.00
 AP Invoices    235435  337.00  
 AP Invoices    444323  228.00  
 AP Invoices    576432  248.00 

Second Supplier
 A B    C D
 B    F
EOL;

$array = preg_split("~[\n\r]+~", $string);

foreach ($array as $value) {
    if (strpos($value, " ") == 0) {
        if (strlen(trim($value)) > 0) {
            echo "\t".$header.rtrim($value).PHP_EOL;
        }
    }
    else {
        $header = $value;
    }
}

点击执行代码后,您可以在工作中看到它{(3}}。

相关问题