只打印列表中的特定单词,不包含其他单词

时间:2017-11-22 01:47:01

标签: python python-2.7

嗨,谢谢你阅读我的问题。我在Windows 7上使用Python 2.7。作为一个新手,我有一个关于如何使用列表中的特定单词打印行号的问题。

首先,列表是:

MainBoard Serial Number,OPS40217,8030dc8edca9,
MainBoard Version,4,,
Model,BoVaConnected,905-0321,
Nucleo URL, nucleo.cloud.com
QAState,QA_STATE_APPROVED
Serial Number,OPS40217,8030dc8edca9,P

从列表中,您可以看到有两个序列号' (第一行和最后一行)。但我想提取包含关键字'序列号'的最后一个行号。只是,不包括其他的话。

我目前的代码是:

lines = list.split('\n')
SN = 'Serial Number'
for i, line in enumerate(lines):
    if SN in line:  # or word in line.split() to search for full words
        sn = i + 1
        print sn

从我的代码中,打印输出有两个行号(第一行和最后一行号)。那么有没有办法只索引特定的关键字行号?感谢。

2 个答案:

答案 0 :(得分:0)

您必须在逗号上分割每一行,然后检查您的目标短语是否在每行的短语列表中。

for i, line in enumerate(lines):
    if SN in line.split(','):  # or word in line.split() to search for full words
        print i + 1

会这样做吗?

答案 1 :(得分:0)

您是否尝试过使用列表?

container = [ ]
SN = 'Serial Number'
for i, line in enumerate(lines):
    if SN in line:
        sn = i + 1
        container.append( 'sn' )

print container[container.length() - 1]