我想创建一个程序来读取文本文件并搜索短语“ 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/

10-13 01:22