我目前正在使用Python中的非常大的文件
junk
junk
junk
--- intermediate:
1489 pi0 111 [686] (1491,1492)
0.534 -0.050 -0.468 0.724 0.135
1499 pi0 111 [690] (1501,1502)
-1.131 0.503 12.751 12.812 0.135
--- final:
32 e- 11 [7]
9.072 20.492 499.225 499.727 0.001
33 e+ -11 [6]
-11.317 -17.699 2632.568 2632.652 0.001
12 s 3 [10] (91) >43 {+5}
2.946 0.315 94.111 94.159 0.500
14 g 21 [11] (60,61) 34>>16 {+7,-6}
-0.728 3.329 5.932 6.907 0.950
------------------------------------------------------------------------------
junk
junk
--- intermediate:
repeat
我想把“---final”行之后的每两行合并到“-------------”行。例如,我想要一个输出文件来读取
^{pr2}$请注意我是如何省略不带空格的行中的额外条目的。我目前的做法是
start = False
for line in myfile:
line = line.strip()
fields = line.split()
if len(fields)==0:
continue
if not start:
if fields[0] == "----final:":
start = True
continue
len(fields)==0应在“--------”行结束脚本并继续,直到它看到另一个“----final”行。我目前不知道如何将这两行合并在一起,同时忽略没有空格的行中的额外信息。有什么建议吗?在
一种快速而肮脏的方法来合并其他行:
注意,我在这里考虑到所有要合并的行都被提取并放入一个名为
lines
的列表中,并且我只是硬编码了从每一行中保留的元素的数量(4)。在只要你知道你想要的部分周围的确切线条:
其中
large_text
是作为巨型字符串导入的文件。在编辑 为了打开文件_文本.txt'作为字符串,请尝试以下操作:
^{pr2}$假设
split(" ")
为split("\t")
应该是赢家 添加了格式固定到一组行。同样的假设也成立。在
您可以使用更新的^{} 模块和一些正则表达式来解决您的问题:
它在行首或空格处查找
- final:
,然后在匹配- final:
后紧跟数字(研究explanation on regex101.com以获取更多详细信息)。然后用制表机将匹配的项目连接起来。在
相关问题 更多 >
编程相关推荐