gpt4 book ai didi

python - if 字符串在行和下一行

转载 作者:行者123 更新时间:2023-12-01 06:42:43 25 4
gpt4 key购买 nike

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

xml(称为 diff):

 <result type="MLST" value="96">
<result_data type="profile" value="43,47,49,49,41,15,3"/>
<result_data type="QC_minimum_consensus_depth" value="7"/>
<result_data type="QC_max_percentage_non_consensus_base" value="10.0"/>
<result_data type="QC_percentage_coverage" value="100"/>
<result_data type="QC_minimum_consensus_depth_for_all_loci" value="7,17,27,10,25,18,22" diff:update-attr="value:7,17,27,10,24,18,22"/>
<result_data type="QC_complete_pileup" value="TRUE"/>
<result_data type="QC_mean_consensus_depth" value="17.67"/>
<result_data type="QC_max_percentage_non_consensus_base_for_all_loci" value="10.0, 6.25, 3.45, 9.09, 5.88, 5.26, 5.41"/>
<result_data type="QC_mean_consensus_depth_for_all_loci" value="17.67, 32.49, 34.09, 23.44, 35.57, 29.02, 39.08" diff:update-attr="value:17.67, 32.49, 34.09, 23.44, 34.24, 29.02, 39.08"/>
<result_data type="QC_traffic_light" value="GREEN"/>
<result_data diff:insert="" type="predicted_serotype" diff:add-attr="type;value" value="('Schwarzengrund (Achtman)', 168), ('Schwarzengrund (PHE)', 83), ('Blockley (Achtman)', 1), ('Uppsala (Achtman)', 1), ('Oslo (Achtman)', 1), ('Schwarzengru (Achtman)', 1), ('Iv Rough:Z4,Z32:- (Achtman)', 1)"/>
<result_data type="predicted_serotype" value="('Schwarzengrund (PHE)', 13)" diff:delete=""/>
</result>
<gastro_prelim_st reason="not novel" success="false">
<type st="96"/>
</gastro_prelim_st>

代码:

diff_list = diff.split("\n")    
for n,line in enumerate(diff_list):
if "predicted_serotype" in line:
print(line)

我想要的是,如果你在一行中定义“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)

这样可以避免索引错误

关于python - if 字符串在行和下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59375861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com