在本例中,有3个类,分别由值0、1和2表示。我想从另一个名为fileA.txt的文本文件中提取属于类1的信息。我想知道如何使用python来解决这个问题。例如:
class.txt
0
0
1
2
2
1
1
fileA.txt
a=[1,3,2,1]
b=[3,2]
c=[3,2,1]
d=[3,3]
e=[4,5,6]
f=[3,2,3]
g=[2,2]
预期输出:c=[3,2,1]
f=[3,2,3]
g=[2,2]
有人能帮我吗?
读取"class.txt"文件并创建类列表:
with open("class.txt", "rt") as f:
classes = [int(line) for line in f.readlines()]
读取"fileA.txt"文件并创建正确的行列表:
with open("fileA.txt", "rt") as f:
lines = [line for index, line in enumerate(f.readlines()) if classes[index] == 1]
显示结果:
print "".join(lines)
不是Python的解决方案,但我喜欢它:)
$ grep -n "^1$" class.txt | cut -d: -f1 | while read linenumber
do
sed -n "${linenumber}p" < fileA.txt
done
输出:c=[3,2,1]
f=[3,2,3]
g=[2,2]
使用的工具有:
-
grep
-
cut
-
sed
这是一种直观的方法
classes = [l.strip() for l in open("class.txt").readlines()]
indices = [i for i, x in enumerate(classes) if x == "1"]
with open('fileA.txt') as file:
for index,line in enumerate(file):
if(index in indices):
print(line)