文件夹中有一堆文本文件,如下所示:
Impedance = 92.01 ohms
Begin Post processing
Loss per inch @ 4 GHz = -0.481 dB
Loss per inch @ 8 GHz = -0.849 dB
Xtalk #1 (Conductor 1 2):
Step response Next= -2.91 mV
Step response Fext peak @ 5 inches= 0.18 mV
Xtalk #2 (Conductor 5 6):
Step response Next= -2.91 mV
Step response Fext peak @ 5 inches= 0.18 mV
Finished post processing
Target: 11.82.
这些行的位置可能会更改,也可能是这些行的重复。我已经编写了以下代码来解析它们,但是我只能检索诸如:Loss per inch @ 4 GHz = -0.481 dB
之类的第一行,而不能检索下一行每英寸损失行。
还有Xtalk #1 (Conductor 1 2):
Step response Next= -2.91 mV
,但不是下一行。
代码如下:
f = open(OutputFolder + '\_' + filename +'_LOG.txt')
s = f.read()
m = re.search("GHz\s+\=(.*)dB",s)
if m:
Lossval = float(m.group(1))
print("Loss Value for filename " + filename + "is :", Lossval)
n = re.search("Impedance\s+\=(.*)ohms",s)
if n:
Zc = float(n.group(1))
我将如何修改代码以捕获除Begin Post processing
行之外的所有值,并将其转储到csv文件中,并以LHS作为列名并将RHS作为其值?
答案 0 :(得分:1)
re.search
仅返回第一个匹配项。要查找所有匹配项,请使用re.findall
>>> re.findall(r"GHz\s+\=(.*)dB",s)
[' -0.481 ', ' -0.849 ']
答案 1 :(得分:0)
您可以使用readlines()而不是read()来获取文件中的所有行,然后迭代所有行:
lines = f.readlines()
for s in lines:
# To get the Xtalk #
xtalk = re.search(r"Xtalk", s)
if xtalk is not None:
= re.split(' ', xtalk.string)
num = int(a[1][1])
...
m = re.search("GHz\s+\=(.*)dB",s)
...