gpt4 book ai didi

python - 用于查找单词的代码无法创建正确的输出

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

我想创建一个程序来读取文本文件并搜索短语“CATEGORIE ANIMALI”然后当它找到它时,我希望它搜索“UCCELLO”和“ANFIBIO”,当它找到“ANFIBIO”时,我希望它继续读取下一个“CATEGORIE ANIMALI”的文件这是文本文件:

CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = tucano
ANFIBIO = rana
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rospo
RETTILE
CATEGORIA ANIMALI
MAMMIFERO
PESCE
UCCELLO = gru
ANFIBIO = rana
RETTILE

这是代码

file = open('testfile.txt', 'r')

search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

for line in file.readlines():
reserveMarker += 1
if line.find(search_phrase1) >= 0:
markerInd1 += 1
print(line)
for line in file.readlines():
if line.find(search_phrase2) >= 0:
markerInd2 += 1
print(line)
elif line.find(search_phrase3) >= 0:
markerInd3 += 1
print(line)
break

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)

我希望获得的输出:

CATEGORIE ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIE ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
19

它到底是什么样的:

CATEGORIE ANIMALI

CATEGORIE ANIMALI

CATEGORIE ANIMALI

3
0
0
19

最佳答案

我会使用with open而不是open,以便文件正确关闭。您也不需要第二个 for 循环。我认为这主要是你的问题所在。需要删除该内容和 break。请参阅下面的示例。

import os


search_phrase1 = "CATEGORIA ANIMALI"
search_phrase2 = "UCCELLO"
search_phrase3 = "ANFIBIO"
markerInd1 = 0
markerInd2 = 0
markerInd3 = 0
reserveMarker = 0

with open('testfile.txt', 'r') as file:
for line in file.readlines():
reserveMarker += 1

if search_phrase1 in line:
markerInd1 += 1
print(line)
if search_phrase2 in line:
markerInd2 += 1
print(line)
elif search_phrase3 in line:
markerInd3 += 1
print(line)

print(markerInd1)
print(markerInd2)
print(markerInd3)
print(reserveMarker)

结果:

CATEGORIA ANIMALI

UCCELLO = tucano

ANFIBIO = rana

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rospo

CATEGORIA ANIMALI

UCCELLO = gru

ANFIBIO = rana

3
3
3
18 # I got 18 instead of 19 so I think you have an extra blank line in your data.

关于python - 用于查找单词的代码无法创建正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60308915/

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