作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在为飞行模拟器构建场景,需要弄清楚如何编辑文本文件中的多行(其中 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/
我是一名优秀的程序员,十分优秀!