python - 使用 python 重新排列文本文件中的数据时遇到麻烦

标签 python

我正在编写一个可以做很多奇怪事情的代码。其中奇怪的事情之一是它生成一个名为 combined.glm 的文件,该文件的内容如下所示:

object line_space {
    content;
    content;
}

object line_conf {
    content;
    content;
}
#2 more line_conf objects

object line_ug { 
    content;
    content;
}
#70 more line_ug

object nod_l {
    content;
    content;
}
#65 more nod_l

我想将所有 nod_l 部分移至 line_ug 部分之上,即紧接在 line_conf 部分之后。我尝试做的方式是这样的:

...
noding=open("combined.glm",'r').readlines()
combined_order=open("combined_order.glm",'w')
for ko,comblineo in enumerate(noding):
    if 'object line_space {' in comblineo:
        combined_order.writelines(noding[ko:ko+5])
for kt,comblinet in enumerate(noding):
    if 'object line_conf {' in comblinet:
        combined_order.writelines(noding[kt:kt+5])
for kr,combliner in enumerate(noding):
    if 'object nod_l {' in combliner:
        combined_order.writelines(noding[kr:kr+5])
for kf,comblinef in enumerate(noding):
    if 'object line_ug' in comblinef:
        combined_order.writelines(noding[kf:kf+5])
...

但它不起作用(在我看来,这是有道理的)。我正确复制了大约 28 个 nod_l,然后是许多 null 字符和大约 16 个 line_ug,然后是另一个 nod_l 并中断。我不确定发生了什么事。

最佳答案

这很脏,但它有效。

import re

old = open("combined.glm").read()

space = re.compile("object line_space {.*?}",re.DOTALL + re.MULTILINE)
conf = re.compile("object line_conf {.*?}",re.DOTALL + re.MULTILINE)
ug = re.compile("object line_ug {.*?}",re.DOTALL + re.MULTILINE)
nod = re.compile("object nod_l {.*?}",re.DOTALL + re.MULTILINE)

all_space = space.findall(old)
all_conf = conf.findall(old)
all_ug = ug.findall(old)
all_nod = nod.findall(old)

with open("combined_order.glm","w") as f:
    for thing in all_space:
        f.write(thing + "\n\n")
    for thing in all_conf:
        f.write(thing + "\n\n")
    for thing in all_nod:
        f.write(thing + "\n\n")
    for thing in all_ug:
        f.write(thing + "\n\n")

关于python - 使用 python 重新排列文本文件中的数据时遇到麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245709/

相关文章:

python字典分配不按顺序

python - 查找从 (x,y) 坐标移动的距离

python - Django 教程 1 错误

python - 在层次结构中显示类别和子类别

Python 解析时出现意外的 EOF

python - cx_Oracle 中的用户输入变量?

javascript - Excel/CSV 与站点的连接

python - 如何以编程方式为 Django 中的给定模型生成 CREATE TABLE SQL 语句?

Python - 匹配变量正则表达式,包括双括号

python - 使用 matplotlib.animation 从 matplotlib 制作视频后创建的空 .mp4 文件