gpt4 book ai didi

python - 提取文件的一部分并使用 python 打印

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:37 24 4
gpt4 key购买 nike

我想提取部分文件内容。以 (“头” 开头并以 ("arraydat"

文件内容:

(record
( "head"
(record
( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
[ "" ]
)
( "numel" 192)
( "mux" 1)
( "freq" 3400000)
( "date" 63602497416.093)
( "focus" 0.066)
( "probID" 574)
( "te" 0)
( "therm" 0)
( "bipolar" "N/A")
( "maker" "YMS")
( "PartNum" 5418916)
( "numrow" 1)
)
)
( "arraydat"
(record
( "FL6" 1625283.947393933)
( "FH6" 4932875.254089763)
( "FL20" 1283607.261269079)
( "FH20" 5673248.882271254)
( "Fc" 3279079.600741847)
( "BW" 100.8695033187829)
( "PW6" 3.316821935120381E-007)
( "PW20" 9.740000000000003E-007)
( "PW30" 1.456E-006)
( "PW40" 2.628000000000001E-006)
( "LG" -46.35823409318354)
( "TOF" -1.363659434369523E-008)
)

我需要提取“head”之后和“arraydat”之前的文件内容。 我已经尝试过这个命令,但没有成功

import re
with open('sample.txt','r') as new_file:
data = new_file.read()
pattern = re.compile(r'\s[(]\s"head"[\s\S]*?\s[(]\s"arraydat"')
stringtext = re.findall(pattern, data)
print(stringtext)

输出应如下所示:

    ( "pname" "C16D")
( "ptype" "probe")
( "sn" "11224")
( "rev" "1")
( "opname" "Kaji")
( "comm"
[ "" ]
)
( "numel" 192)
( "mux" 1)
( "freq" 3400000)
( "date" 63602497416.093)
( "focus" 0.066)
( "probID" 574)
( "te" 0)
( "therm" 0)
( "bipolar" "N/A")
( "maker" "YMS")
( "PartNum" 5418916)
( "numrow" 1)
)
)

最佳答案

data = []
read = False

for line in open('test.dat'):
if line.strip() == '( "head"':
read = True
continue
elif line.strip() == '( "arraydat"':
read = False
if read:
data.append(line.rstrip())

print('\n'.join(data))

关于python - 提取文件的一部分并使用 python 打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39248101/

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