Python Else语句未被执行
我有一个文本文件,可以读取。我设法将所有内容排序,但我不明白的是,我的代码没有在else语句中执行。(Else语句将跳过无用数据,不会添加到PriorityQueue。) id_为_g0000515 num_为0.92 id_为_g0000774 uselessdata2 数值为1.04 至此 id_为_g0000377 数值为1.01 pt21 id_为_g0000521 数值为5.6Python Else语句未被执行,python,if-statement,io,priority-queue,Python,If Statement,Io,Priority Queue,我有一个文本文件,可以读取。我设法将所有内容排序,但我不明白的是,我的代码没有在else语句中执行。(Else语句将跳过无用数据,不会添加到PriorityQueue。) id_为_g0000515 num_为0.92 id_为_g0000774 uselessdata2 数值为1.04 至此 id_为_g0000377 数值为1.01 pt21 id_为_g0000521 数值为5.6 find不会做你认为它会做的事情。它返回正在查找的字符串的索引,如果找不到字符串,则返回-1。在if语句中,
find
不会做你认为它会做的事情。它返回正在查找的字符串的索引,如果找不到字符串,则返回-1。在if
语句中,除了0
之外的所有整数都是“truthy”(例如,bool(-1)为True,bool(0)为False,bool(1)为True
)。由于没有任何字符串包含“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()
没有
line.skip()
方法;只要去掉整个else
块,就可以忽略行了。。继续下一行,我试着继续读jibberish。它仍然添加到优先级队列中,这些行随后包含两个字符串中的一个。我很好奇是什么让您尝试line.skip()
。抱歉,这是一个错误。。我本想把线接上的。下一步()难怪我的线会输出奇怪的输出。这一切都是从.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()