在这种情况下,有3个类由值0,1和2表示。我想从另一个名为fileA.txt的文本文件中提取属于类1的信息。我想知道如何使用python解决这个问题。
例如:
class.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]
fileA.txt
c=[3,2,1]
f=[3,2,3]
g=[2,2]
预期输出:
<ui-select ng-model="country.selected" theme="selectize" ng-disabled="disabled" style="width: 300px;">
<ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
<ui-select-choices repeat="country in countries | filter: $select.search">
<span ng-bind-html="country.name | highlight: $select.search"></span>
<small ng-bind-html="country.code | highlight: $select.search"></small>
</ui-select-choices>
</ui-select>
任何人都可以帮助我吗?
答案 0 :(得分:2)
阅读&#34; class.txt&#34;文件并创建类列表:
with open("class.txt", "rt") as f:
classes = [int(line) for line in f.readlines()]
阅读&#34; fileA.txt&#34;文件并创建正确的行列表:
with open("fileA.txt", "rt") as f:
lines = [line for index, line in enumerate(f.readlines()) if classes[index] == 1]
显示结果:
print "".join(lines)
答案 1 :(得分:1)
不是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]
使用的工具是:
答案 2 :(得分:1)
这是一种直观的方法
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)