gpt4 book ai didi

python - 如何用信息填充空白,同时保持其余部分不变?

转载 作者:行者123 更新时间:2023-12-01 02:29:42 24 4
gpt4 key购买 nike

我正在为飞行模拟器构建场景,需要弄清楚如何编辑文本文件中的多行(其中 3,579,189 行)。

我有 TextCrawler Pro、Node、Python SVN 和 Notepad++ 作为工具。

原始、预编辑部分:

POLYGON_POINT -79.750000000217,42.017498354525,0
POLYGON_POINT -79.750000000217,42.016478251402,0
POLYGON_POINT -79.750598748133,42.017193264943,0
POLYGON_POINT -79.750000000217,42.017498354525,0


POLYGON_POINT -79.750000000217,42.085882815878,0
POLYGON_POINT -79.750000000217,42.082008734634,0
POLYGON_POINT -79.751045507507,42.082126409633,0
POLYGON_POINT -79.750281907508,42.083166574215,0
POLYGON_POINT -79.750781149174,42.084212672130,0
POLYGON_POINT -79.750000000217,42.085882815878,0


POLYGON_POINT -79.750000000217,42.088955814831,0
POLYGON_POINT -79.750456566883,42.087544672125,0
POLYGON_POINT -79.751642899173,42.088273325249,0
POLYGON_POINT -79.751461052298,42.088916154415,0
POLYGON_POINT -79.750000000217,42.088955814831,0

使用 Notepad++ 的替换功能,可以很容易地添加 POLYGON_POINT 行。现在我需要一些帮助才能使其显示如下:

BEGIN_POLYGON
POLYGON_POINT -79.750000000217,42.017498354525,0
POLYGON_POINT -79.750000000217,42.016478251402,0
POLYGON_POINT -79.750598748133,42.017193264943,0
POLYGON_POINT -79.750000000217,42.017498354525,0
END_POLY
BEGIN_POLYGON
POLYGON_POINT -79.750000000217,42.085882815878,0
POLYGON_POINT -79.750000000217,42.082008734634,0
POLYGON_POINT -79.751045507507,42.082126409633,0
POLYGON_POINT -79.750281907508,42.083166574215,0
POLYGON_POINT -79.750781149174,42.084212672130,0
POLYGON_POINT -79.750000000217,42.085882815878,0
END_POLY
BEGIN_POLYGON
POLYGON_POINT -79.750000000217,42.088955814831,0
POLYGON_POINT -79.750456566883,42.087544672125,0
POLYGON_POINT -79.751642899173,42.088273325249,0
POLYGON_POINT -79.751461052298,42.088916154415,0
POLYGON_POINT -79.750000000217,42.088955814831,0

即在每个 block 之前添加 BEGIN_POLYGON,在每个 block 之后添加 END_POLY

我该怎么做?

最佳答案

我将使用 itertools.groupby 通过是否为空来对行进行分组(仅采用 if k 条件的非空白组),并为每个组添加页眉/页脚。然后使用 itertools.chain 展平组

import itertools

with open("file.txt") as f, open("fileout.txt","w") as fw:
fw.writelines(itertools.chain.from_iterable([["BEGIN_POLYGON\n"]+list(v)+["END_POLYGON\n"] for k,v in itertools.groupby(f,key = lambda l : bool(l.strip())) if k]))

key = lambda l : bool(l.strip()))是分组键:测试空行但行终止

此方法不需要完整读取文件,因此适合非常大的文件。它逐行处理文件,因此不会占用内存。

关于python - 如何用信息填充空白,同时保持其余部分不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46969719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com