[英]Extracting from specific lines in a text file loop
我有一个看起来像这样的文件
--------------Time step: 1 ---------------
Accumulated rewards: 1.5
Alpha: 660
Beta: 173
TCP_Friendliness: 1
Fast_Convergence: 1
State: 3
Retries: 0.0
---------------------------------------------------------------
---------------Time step: 2 ---------------
Accumulated rewards: 2.724744871391589
Alpha: 193
Beta: 0
TCP_Friendliness: 0
Fast_Convergence: 0
State: 3
Retries: 0.0
---------------------------------------------------------------
---------------Time step: 3 ---------------
Accumulated rewards: 3.869459113944921
我想将时间步长值提取到 X 数组中,将累积奖励值提取到 Y 数组中,我不知道该怎么做,因为我有 0 python 经验,但这是我写的初始循环跳过示例中未包含的前几行(乱码数据)
with open('Tuner_result_1.txt') as f:
for _ in range(11):
next(f)
for line in f:
x = [line.split()[0]]
y = [line.split()[1]]
显然,第二个 for 中的操作是不正确的,我不确定如何以我想要的方式正确阅读我想要的行。
myfile = open("Tuner_result_1.txt", "rt") # open lorem.txt for reading text
contents = myfile.read() # read the entire file into a string
myfile.close() # close the file
#print(contents)
import re
X = re.findall("Time step: ([0-9]+)", contents)
Y = re.findall("Accumulated rewards: ([0-9.]+)", contents)
print(X)
print(Y)
Output:
['1', '2', '3']
['1.5','2.724744871391589','3.869459113944921']
您可以应用下一个正则表达式: Time step: (\d+).+?Accumulated rewards: ([\d\.]+)
。
代码:
import re
with open("filename") as f:
X, Y = zip(*re.findall("Time step: (\d+).+?Accumulated rewards: ([\d\.]+)",
f.read(), re.MULTILINE | re.DOTALL))
您可以单独处理每个匹配项:
X = []
Y = []
with open("filename") as f:
for match in re.finditer("Time step: (\d+).+?Accumulated rewards: ([\d\.]+)",
f.read(), re.MULTILINE | re.DOTALL))
x, y = match.groups()
# do smth with x and y or add to list
X.append(x)
Y.append(y)
您还可以使用字符串切片:
X = []
Y = []
with open("filename") as f:
s = f.read()
x_idx = y_idx = 0
while True:
x_idx = s.find("Time step: ", y_idx)
y_idx = s.find("Accumulated rewards: ", x_idx)
if x_idx >= 0 and y_idx >= 0:
x = s[x_idx + 11: s.find(" ", x_idx + 11)]
y = s[y_idx + 21: s.find("\n", y_idx + 21)]
# do smth with x and y or add to list
X.append(x)
Y.append(y)
else:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.