else语句没有被执行

Else statement did not get executed

我有一个文本文件可以读取。我设法对所有内容进行了排序,但我不明白的是我的代码没有在 else 语句中执行。 (Else语句会跳过无用的数据,不会加入到PriorityQueue中。)

id_is_g0000515

num_is_0.92

id_is_g0000774

uselessdata2

num_is_1.04

hithere

id_is_g0000377

num_is_1.01

pt21

id_is_g0000521

num_is_5.6

import os, sys, shutil, re


def readFile():
    from queue import PriorityQueue
    str1 = 'ID_IS'
    str2 = 'NUM_IS'
    q = PriorityQueue()
    #try block will execute if the text file is found
    try:
        fileName= open("Real_format.txt",'r')
        for line in fileName:
                for string in line.strip().split(','):
                    if string.find(str1): #if str1 is found
                        q.put(string[-4:]) #store it in PQ
                    elif string.find(str2):#if str2 is found
                        q.put(string[-8:]) #store it in PQ
                    else:
                        line.next() #skip the useless string
                        #q.remove(string)

        fileName.close() #close the file after reading          
        print("Displaying Sorted Data")
        #print("ID TYPE       Type")
        while not q.empty():
            print(q.get())

            #catch block will execute if no text file is found
    except IOError:
                print("Error: FileNotFoundException")
                return

readFile()

find 并不像您想象的那样。它 returns 正在查找的字符串的索引,如果未找到字符串则为 -1。在 if 语句中,除 0 之外的所有整数都是 "truthy"(例如,bool(-1) is True and bool(0) is False and bool(1) is True)。由于 none 个字符串包含 'ID_IS',string.find(str1) 始终为 -1,这是正确的...因此第一个 if 命中并将字符串添加到队列中。

您应该将字符串转换为大写进行比较,并使用 startswith 而不是 find

import os, sys, shutil, re


def readFile():
    from queue import PriorityQueue
    str1 = 'ID_IS'
    str2 = 'NUM_IS'
    q = PriorityQueue()
    #try block will execute if the text file is found
    try:
        fileName= open("Real_format.txt",'r')
        for line in fileName:
                # from the sample text, the split is pointless but harmless
                for string in line.strip().split(','):
                    if string.upper().startswith(str1): #if str1 is found
                        q.put(string[-4:]) #store it in PQ
                    elif string.upper().startswith(str2):#if str2 is found
                        q.put(string[-8:]) #store it in PQ

        fileName.close() #close the file after reading          
        print("Displaying Sorted Data")
        #print("ID TYPE       Type")
        while not q.empty():
            print(q.get())

            #catch block will execute if no text file is found
    except IOError:
                print("Error: FileNotFoundException")
                return

readFile()