如何只读取文本文件的第 26 列?
How do I read only the 26th column from a textfile?
我的 .txt 文件看起来是这样的:
=== Predictions on test data ===
inst# actual predicted error prediction (6)
1 1:1 6:6 + 0.753 (0)
2 1:1 6:6 + 0.753 (0)
3 1:1 5:5 + 0.975 (2)
4 1:1 5:5 + 1 (11)
5 1:1 5:5 + 0.992 (0)
6 1:1 6:6 + 0.941 (0)
7 1:1 3:3 + 0.857 (0)
8 1:1 2:2 + 0.967 (0)
9 1:1 2:2 + 1 (0)
10 1:1 5:5 + 1 (97)
11 1:1 5:5 + 0.956 (0)
12 1:1 5:5 + 1 (1)
13 1:1 5:5 + 0.958 (59)
14 1:1 5:5 + 0.969 (0)
15 1:1 5:5 + 0.984 (0)
16 1:1 4:4 + 0.8 (0)
17 1:1 5:5 + 1 (141)
18 1:1 5:5 + 0.974 (5)
如何只读取 "predicted" 列中的第一个值?特别是,数值出现在每行的第 26 列(比方说)?
我写了一个python脚本:
f = open("out_grasp_R.txt", 'r')
f.readline()
f.readline()
f.readline()
for line in f:
f.read(25)
print(f.read(1))
f.readline()
我收到一条错误消息说 "mixing iteration and read methods would lose data"
我想要一个像这样的数组:
[6,6,5,....]
我该怎么办?
从第三列拆分取第一个元素更简单
with open("out_grasp_R.txt", 'r') as f:
next(f)
print([line.split()[2][0] for line in f])
['6', '6', '5', '5', '5', '6', '3', '2', '2', '5', '5', '5', '5', '5', '5', '4', '5', '5']
如果您确定间距,请使用 print([line[21] for line in f])
,它根据您的输入文件对应于您想要的数据。除非您考虑空格列,否则您实际上有六列。
您可以获取行字符串并像数组一样对其进行索引。
print(line[25])
或者制作数组:
array.append(line[25])
这确实需要您确定它总是一行中的第 26 个字符。
使用readlines
方法,你得到每行的字符串列表:
filename = 'out_grasp_R.txt'
with open(filename) as f:
content = f.readlines()
predicted = []
for line in content:
predicted.append(int(line.split()[2][0]))
print predicted
[6, 6, 5, 5, 5, 6, 3, 2, 2, 5, 5, 5, 5, 5, 5, 4, 5, 5]
我的 .txt 文件看起来是这样的:
=== Predictions on test data ===
inst# actual predicted error prediction (6)
1 1:1 6:6 + 0.753 (0)
2 1:1 6:6 + 0.753 (0)
3 1:1 5:5 + 0.975 (2)
4 1:1 5:5 + 1 (11)
5 1:1 5:5 + 0.992 (0)
6 1:1 6:6 + 0.941 (0)
7 1:1 3:3 + 0.857 (0)
8 1:1 2:2 + 0.967 (0)
9 1:1 2:2 + 1 (0)
10 1:1 5:5 + 1 (97)
11 1:1 5:5 + 0.956 (0)
12 1:1 5:5 + 1 (1)
13 1:1 5:5 + 0.958 (59)
14 1:1 5:5 + 0.969 (0)
15 1:1 5:5 + 0.984 (0)
16 1:1 4:4 + 0.8 (0)
17 1:1 5:5 + 1 (141)
18 1:1 5:5 + 0.974 (5)
如何只读取 "predicted" 列中的第一个值?特别是,数值出现在每行的第 26 列(比方说)?
我写了一个python脚本:
f = open("out_grasp_R.txt", 'r')
f.readline()
f.readline()
f.readline()
for line in f:
f.read(25)
print(f.read(1))
f.readline()
我收到一条错误消息说 "mixing iteration and read methods would lose data"
我想要一个像这样的数组:
[6,6,5,....]
我该怎么办?
从第三列拆分取第一个元素更简单
with open("out_grasp_R.txt", 'r') as f:
next(f)
print([line.split()[2][0] for line in f])
['6', '6', '5', '5', '5', '6', '3', '2', '2', '5', '5', '5', '5', '5', '5', '4', '5', '5']
如果您确定间距,请使用 print([line[21] for line in f])
,它根据您的输入文件对应于您想要的数据。除非您考虑空格列,否则您实际上有六列。
您可以获取行字符串并像数组一样对其进行索引。
print(line[25])
或者制作数组:
array.append(line[25])
这确实需要您确定它总是一行中的第 26 个字符。
使用readlines
方法,你得到每行的字符串列表:
filename = 'out_grasp_R.txt'
with open(filename) as f:
content = f.readlines()
predicted = []
for line in content:
predicted.append(int(line.split()[2][0]))
print predicted
[6, 6, 5, 5, 5, 6, 3, 2, 2, 5, 5, 5, 5, 5, 5, 4, 5, 5]