使用python查找文本文件中单词出现的第n个实例

编程入门 行业动态 更新时间:2024-10-28 16:22:51
本文介绍了使用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个实例

本文发布于:2023-11-17 17:00:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   单词   实例   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!