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

3 投票
3 回答
1421 浏览
提问于 2025-04-18 11:19

我正在使用paramiko这个工具登录到一个设备上,执行一些命令,然后只获取相关的输出。相关的代码部分看起来是这样的:

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

现在,从这个输出中,我只想要链接状态,所以我这样做了:

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

一切正常。不过,我想要的是在我的列表推导式中指定出现的次数,这样我就可以只获取第一个、第二个或第n个“Link”这个关键词的出现。

3 个回答

1

在编程中,有时候我们会遇到一些问题或者错误,这些问题可能会让我们感到困惑。比如,有人可能在使用某个功能时,发现它并没有按照预期工作。这种情况很常见,尤其是对于刚开始学习编程的人来说。

解决这类问题的第一步是要仔细检查代码,看看是否有拼写错误或者逻辑上的问题。有时候,简单的错误就会导致程序无法正常运行。

另外,了解你使用的工具或语言的文档也是很重要的。文档通常会提供很多有用的信息,帮助你理解如何正确使用某个功能。

如果你还是无法解决问题,可以考虑在网上寻找帮助,比如在编程社区提问。在提问时,记得描述清楚你遇到的问题,并附上相关的代码,这样别人才能更好地帮助你。

总之,遇到问题时不要着急,慢慢分析,寻找解决方案,编程的过程就是不断学习和解决问题的过程。

occurence = 2
link = [item for item in stdout.read().splitlines() if 'Link' in item][occurence]
1

为什么不直接给你的列表推导式加个索引呢?

links = [item for item in stdout.read().splitlines() if 'Link' in item]
print links[n] # index here
2

你有三个选择。

第一种是把所有的项目放在一个列表里,然后用索引来访问。但这样会在内存中创建一个不必要的列表:

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

第二种是使用 itertools.islice,把你在代码中用到的生成器传给它:

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(),因为它们会把所有内容都读入内存:

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

如果你只想匹配字符串开头的 'Link',可以使用 item.startswith('Link')。但如果你想在字符串的任何位置匹配,就可以忽略这个。

撰写回答