我有一个可读的文本文件。我设法将所有内容排序,但我不明白的是我的代码没有在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()
答案 0 :(得分:1)
find
并不能按照您的想法行事。它返回正在寻找的字符串的索引,如果没有找到字符串则返回-1。在if
语句中,0
以外的所有整数都是" truthy" (例如,bool(-1) is True and bool(0) is False and bool(1) is 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()