如何在上面或下面有空行的行中插入文本?

时间:2017-12-13 22:32:46

标签: regex notepad++

我有一组坐标,用空行随机分隔:

19.815857300 39.791813400
19.816105700 39.791921800
19.816220800 39.791984600
19.816271400 39.792010000

19.786375895 39.678097997
19.783813875 39.677022719
19.782758486 39.676590122

等......很多坐标:)

我想在第一个坐标集的开头和结尾插入一个特定的文本,("段落"的第一行)。 每个段落的最后一行都是相同的 - 不同的文本输入 它们之间的坐标,也需要前后的另一个文本。

所以..我想要实现的结果,应该像

BEGIN_SEGMENT  0 50 10 19.815857300 39.791813400 0.00000000 
SHAPE_POINT            19.816105700 39.791921800           0
SHAPE_POINT            19.816220800 39.791984600           0
END_SEGMENT         20 19.816271400 39.792010000 0.00000000

BEGIN_SEGMENT  0 50 10 19.786375895 39.678097997 0.00000000 
SHAPE_POINT            19.783813875 39.677022719           0
END_SEGMENT         20 19.782758486 39.676590122 0.00000000

etc..etc ..

有关如何使用notepad ++和正则表达式完成此操作的任何想法? Thanx提前!

2 个答案:

答案 0 :(得分:0)

使用python 3.6的解决方案。

它读入一个文件" input.txt" - 逐行 - 直到它变成空行。 在每次启动时,它会重新创建文件" result.txt"。

每个找到的段落都附加在" result.txt" - 直到完成。

现在你只需要获得一个python环境; o)并将它提供给你的文件。

import re
import datetime
import random 

# recreate empty file with timestamp
with open("result.txt","w") as r:
    r.write(str(datetime.datetime.now()) + "\n")

with open("input.txt","r") as f:
    while True:
        paragraph = [] 

        line = f.readline()
        if line == "":
           break # readline always retunrs \n on empty lines until file end reached

        while len(line.strip()) > 0:
            # accumulate lines
            paragraph.append(line.strip())
            line = f.readline()

        if not paragraph:
            continue # jumps back up to while True:

        rv = []
        for idx in range(0,len(paragraph)):
            if idx == 0:
                rv.append("BEGIN_SEGMENT  0 50 " + str(random.randint(1,10000)) + " " + paragraph[idx] + " 0.00000000 " + "\n")
            elif idx != (len(paragraph) - 1):
                rv.append("SHAPE_POINT            " + paragraph[idx] + "           0" + "\n")
            else:
                rv.append("END_SEGMENT         " + str(random.randint(1,10000)) + " " + paragraph[idx] + " 0.00000000" + "\n" + "\n")   

        # append results of paragraph
        with open("result.txt","a") as resFile:
            for line in rv:
                resFile.write(line)

# edited code for random numbers instead of fixed ones

答案 1 :(得分:-1)

不完整 - 您必须手动调整第一行和最后一行。

Step 1 end segment-begin segment
FIND:\r\n(\d.*)\r\n\r\n
REPLACE: \r\nEND_SEGMENT\t$1\r\n\r\nBEGIN_SEGMENT\t
Step 2: shape point
FIND: ^(\d.*)$
REPLACE: SHAPE_POINT\t$1

假设段之间只有一个空行。 您可以使用https://regexper.com/显示表达式图表。