如果您的“numbers.dat”文件在整个文件中包含字符串和数字,这就是我用来解决您的问题的方法。我必须逐个字符地分解行,然后将任何多位数的数字构建到字符串变量 myTemp 中,然后每当没有数字字符时,我检查 myTemp 的大小以及其中是否有任何内容将其转换为整数并将其分配给 myInt,将 myTemp 变量重置为空(因此,如果该行上有另一个数字,它将不会添加到已经存在的数字中),然后将其与当前的 Max 进行比较。这是几个如果,但我认为它可以完成工作。
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
定义主():
myMax= 0
myCount = 0
myTemp = ''
lastCharNum = False
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
for char in line: #go through each character on the line
if is_number(char) == False: #if the character isnt a number
if len(myTemp) == 0: #if the myTemp is empty
lastCharNum = False #set lastchar false
continue #then continue to the next char
else: #else myTemp has something in it
myInt = int(myTemp)#turn into int
myTemp = '' #Flush myTemp variable for next number (so it can check on same line)
if myInt > myMax: #compare
myMax = myInt
else:# otherwise the char is a num and we save it to myTemp
if lastCharNum:
myTemp = myTemp + char
lastCharNum = True #sets it true for the next time around
else:
myTemp = char
lastCharNum = True #sets it true for the next time around
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
主要的()
如果“numbers.dat”文件的每一行只有数字,那么这很容易解决:
def main():
myMax= 0
myCount = 0
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
if int(line) > myMax: #compare
myMax = int(line)
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
主要的()