使用python查找文本文件中单词出现的第n个实例 [英] Find nth instance of occurrence of a word in a text file using python

查看:63
本文介绍了使用python查找文本文件中单词出现的第n个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用paramiko登录设备并运行一些命令,然后仅捕获相关输出.代码的相关部分如下所示:

I am using paramiko to login to a device and run some commands and then capture only the relevant output. The relevant portion of the code looks like this:

stdin, stdout, stderr = ssh.exec_command('show interface')
print stdout.read()

这给出了以下输出:

Ethernet interface 0:0
Internet address:     171.182.204.207 netmask 255.255.255.0
Internet address:     fe80::2d0:83ff:fe06:4c67 prefixlen 64
MTU size:             1500
Link status:          configured to full duplex, 1 gigabit/sec network
Member of the bridge: none
Ethernet interface 0:1
Internet address:     fe80::2d0:83ff:fe06:4c66 prefixlen 64
MTU size:             1500
Link status:          autosensed to full duplex, 1 gigabit/sec network
Member of the bridge: none

现在,我只想要链接状态,所以我这样做了:

Now out of this,I want only the link status,so I did this :

stdin, stdout, stderr = ssh.exec_command('show interface')
link = '\n'.join(item for item in stdout.read().splitlines() if 'Link' in item)
print link

现在我明白了:

Link status:          configured to full duplex, 1 gigabit/sec network
Link status:          autosensed to full duplex, 1 gigabit/sec network

很好.但是,我想要在列表理解中指定出现的位置,这样我就只能获得关键字Link的第一个,第二个或第n个出现.

Works fine.However,what I want is to specify the occurrence in my list comprehension so that I get only the first,second or nth occurrence of the keyword Link.

推荐答案

您有三个选择.

将所有项目存储在列表中,然后使用索引.但这会在内存中创建不必要的列表:

Store all the items in a list and then use indexing. But this will create an unnecessary list in memory:

links = [item for item in stdout.read().splitlines() if 'Link' in item]
index = 5
print links[index]


或使用 itertools.islice ,并将您在代码中使用的生成器传递给它:


Or use itertools.islice, and pass it the generator created you've used in your code:

from itertools import islice
index = 5
links = (item for item in stdout.read().splitlines() if 'Link' in item)
print next(islice(links, index, index+1))


或者甚至更好地将 itertools.islice 与以下生成器一起使用.这是我不使用 .read() .splitlines()的原因,因为它们将所有内容读入内存:


Or even better use itertools.islice with the following generator. Here's I am not using either .read() or .splitlines() as they read everything into memory:

links = (item for item in stdout if 'Link' in item)
print next(islice(links, index, index+1))


如果只想在字符串的开头匹配'Link',也可以使用 item.startswith('Link'),但是如果想要在字符串中的任何地方匹配它,然后忽略它.


You can also use item.startswith('Link') in case you only want to match 'Link' only at the start of the string, but if you want to match it anywhere in the string then ignore this.

这篇关于使用python查找文本文件中单词出现的第n个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆