假设文件中有一个表:
VLan Interface State
Vlan1 Fa0/0 Up
Vlan2 Fa0/1 Down
Vlan3 Fa0/3 Up
现在我真的需要得到VLan&的名称。状态为up的接口。 但为此,我首先需要拆分表格。 我是python的新手,无法弄清楚如何分割这个表。
答案 0 :(得分:2)
迭代第二行中的行(使用 next
)并检查状态是否为 Up 并附加它们(或做任何你想做的事情)喜欢这样做。
with open('test.txt','r') as f:
next(f)
l = [line.split()[1] for line in f if line.split()[2] == "Up"]
print(l)
输出:
['Fa0/0', 'Fa0/3']
不过,即使你没有使用next
,也没关系。
答案 1 :(得分:0)
考虑到您的数据包含在public class PlayToneService extends IntentService {
public PlayToneService() {
super(PlayToneService.class.getName());
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
// play tone
try {
ToneGenerator toneGenerator= new ToneGenerator(AudioManager.STREAM_SYSTEM, ToneGenerator.MAX_VOLUME);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
Thread.sleep(200);
toneGenerator.stopTone();
toneGenerator.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这里用于以结构化方式提取内容的代码,并仅筛选出data/table.txt
Up
结果:file_path = 'data/table.txt'
with open(file_path) as f:
content = f.readlines()
# it removes the empty lines
clean_content = [l for l in content if l != '\n']
# remove the line terminator for each line
lines = [l.replace('\n', '') for l in clean_content]
# attributes of the dictionary
dict_attrs = lines[0].split()
interfaces = [dict(zip(dict_attrs, l.split())) for l in lines[1:]]
interfaces_up = [i for i in interfaces if i['State'] == 'Up']