简体   繁体   English

在Notepad ++或使用Python合并行

[英]Merging lines in Notepad++ or by using Python

I have a long file which is structured like below: 我有一个长文件,其结构如下:

  • every line should start with 500 每行应以500开头
  • there are lines not starting with 500 (Line 2, Line 4, basically every even line) 有些行不是以500开头(第2行,第4行,基本上是每偶数行)

What I want to do: 我想做的事:

  • The lines not starting with 500 should be merged with not even line above (so Line 2 with Line 1, Line 4 with Line 3, etc). 不以500开头的行应与上方的偶数行合并(因此,第2行与第1行,第4行与第3行,等等)。
  • Once merging additional semicolon should be added (ie <Line 1>;<Line 2> ). 合并后,应添加其他分号(即<Line 1>;<Line 2> )。

How I can easily do it in python (2.7)? 我如何在python(2.7)中轻松做到这一点?

Regex in Notepad++ may also work. Notepad ++中的正则表达式也可以使用。 I've heard that I should use a multi-line mode but I don't know how to do it. 我听说我应该使用多行模式,但是我不知道该怎么做。 Probably it's not even hard but I have a hard time dealing with it. 也许这还不算困难,但是我很难解决。

Thanks. 谢谢。

Here the input (simplified): 这里的输入(简体):

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”
;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”
;”     6,991.00”;;

屏幕截图记事本++

Expected output: 预期产量:

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;”     6,991.00”;;

Try this regex: 试试这个正则表达式:

[\r\n]+(?!;500)

Replace each match with a ; 用替换每个匹配;

Click for Demo 点击演示

Explanation: 说明:

  • [\\r\\n]+ - matches 1+ occurrences of either a newline character or a carriage return [\\r\\n]+ -匹配1+次以上的换行符或回车符
  • (?!;500) - negative lookahead to make sure that the current position is not followed by :500 (?!;500) -提前否定以确保当前位置不跟在:500

Before Replacing: 更换之前:

在此处输入图片说明

After replacing: 更换后:

在此处输入图片说明

Regex : \\n^(?!;500) 正则表达式\\n^(?!;500)

Details: 细节:

  • ^ Asserts position at start of a line ^在行首处声明位置
  • (?!) Negative Lookahead (?!)负前瞻

Python code : Python代码

text = open(r'C:\....txt').read()
r = re.compile(r'\n^(?!;500)', re.M)
text = r.sub(';', text)

Output: 输出:

;500;616;;”YPO_INV”;”KP”;”51D0072”;”YNU”;;”     6,291.00”;;
;500;6900;;”YPNV”;”KE”;”53213072”;”YOU”;;”     6,991.00”;;

Demo code 演示代码

Use Notepad++ for this kind of simple changes. 使用Notepad++进行这种简单的更改。

  1. Go to Replace menu ( Ctrl + H ) 转到替换菜单( Ctrl + H
  2. Select Regular expressions ( Alt + G ) 选择正则表达式Alt + G
  3. Enter following values: 输入以下值:

    • Find what : [\\r\\n]+(;(?!500)) 找到什么[\\r\\n]+(;(?!500))
    • Replace with : \\1 替换为\\1
  4. Click on Replace All ( Alt + A ) 单击全部替换Alt + A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM