Python 如果字符串在第行和下一行中

Python 如果字符串在第行和下一行中,python,Python,我有一个xml字符串(转换为列表),我正在寻找一个特定的字符串。只有当这个字符串在列表的下一行中有相同的特定字符串时,我才想做一些事情 xml(称为diff): 我想要的是,如果您在第行中定义了“predicted_serotype”,并且下一行也有“predicted_serotype”,那么请打印 感谢您的帮助。我所做的只是将您的xml内容复制到一个txt文件中,然后将其作为字符串读取 file = "path/tmp.txt" # the content will be a variabl

我有一个xml字符串(转换为列表),我正在寻找一个特定的字符串。只有当这个字符串在列表的下一行中有相同的特定字符串时,我才想做一些事情

xml(称为diff):

我想要的是,如果您在第行中定义了“predicted_serotype”,并且下一行也有“predicted_serotype”,那么请打印


感谢您的帮助。

我所做的只是将您的xml内容复制到一个txt文件中,然后将其作为字符串读取

file = "path/tmp.txt"
# the content will be a variable containing string
with open(file, 'r') as file:
    content = file.read()

# diff_list is a list
diff_list = content.split("\n")    
for n,line in enumerate(diff_list):
    print(n)
    if "predicted_serotype" in line and "predicted_serotype" in diff_list[n+1]:
        print(line)
基本上,
diff_list
是一个列表,因此您可以执行所有类型的索引操作

正如评论中提到的其他人一样,确保n+1

没有超出范围

更新@bruno desthuilliers建议:

for line, next_line in zip(diff_list, diff_list[1:]):
    if "predicted_serotype" in line and "predicted_serotype" in next_line:
        print(line)

这样可以避免索引错误

尽管我的答案与问题的字面意义无关,但考虑到问题的上下文,我建议使用正则表达式,如下所示

import re

diff = "Your xml text" 
regx = re.compile("(<.*predicted_serotype.*\/>)\s.*predicted_serotype.*")
matches = regx.findall(diff)

for match in matches:
    print(match)
重新导入
diff=“您的xml文本”
regx=re.compile(“()\s.*预测的血清型。*”)
匹配项=regx.findall(差异)
对于匹配中的匹配:
打印(匹配)

这里,正则表达式匹配包含字符串“predicted_serotype”的两行,但
regx.findall
仅返回括号内的捕获组。

如果行中的“predicted_serotype”和差异列表中的“predicted_serotype”[n+1]:
将执行此操作,但您需要检查
n+1
是否超出范围。首先,您必须找到行数,然后必须对[n]和[n+1]进行检查,如果word存在,则打印。您可以对行使用
,zip中的下一行(diff_列表,diff_列表[1:]):
-这避免了索引错误。很好!你是对的,为什么不更新我的答案:)我让你决定。
for line, next_line in zip(diff_list, diff_list[1:]):
    if "predicted_serotype" in line and "predicted_serotype" in next_line:
        print(line)
import re

diff = "Your xml text" 
regx = re.compile("(<.*predicted_serotype.*\/>)\s.*predicted_serotype.*")
matches = regx.findall(diff)

for match in matches:
    print(match)