我需要确定数字和逗号之间是否有空格,那么该数字无效。因此,如果数字在逗号之间有超过或少于 2 个小数位和/或空格,那么它是无效的,但如果它在逗号之间没有空格并且有 2 个小数位,那么它是一个有效数字。这就是为什么第 1 行中的第一个数字是 VALID
有两种方法,我更喜欢使用方法 2,但我认为如果我使用两种方法,它可能会帮助你们中的任何人添加
#-----------Method 1------------------------------------------
res = 0
outfile = "output2.txt"
baconFile = open(outfile,"wt")
index = 0
invalid_string = "INVALID"
valid_string = "VALID"
with open('file.txt') as file:
for line in file:
carrera = ''
index = index + 1
print("Line {}: ".format(index), end='')
baconFile.write("Line {}: ".format(index))
number_list = line.strip().split(',')
for number in number_list:
if len(number.split('.')[-1]) == 2:
#res += 1
## print("VALID")
carrera = valid_string
if len(number.split('.')[-1]) != 2:
#res += 1
carrera = invalid_string
if len(number.split(',')[-1]) == " ": #checking for whitespace
carrera = invalid_string
print (carrera, end=' ')
baconFile.write(carrera + " ")
print('\n', end='')
baconFile.write('\n')
baconFile.close()
#-----------Method 2------------------------------------------
res = 0
outfile = "output2.txt"
baconFile = open(outfile,"wt")
index = 0
invalid_string = "INVALID"
valid_string = "VALID"
with open('file.txt') as file:
这是我在 Text.file 中的数字列表:
1,1.02, 123.0005
1.02, 1.02 , 1.02
预期的:
Line 1: INVALID VALID INVALID
Line 2: VALID INVALID INVALID (since there's spaces between the last number that's why it is INVALID)
实际的:
Line 1: INVALID VALID INVALID
Line 2: VALID INVALID VALID
潇潇雨雨
桃花长相依
慕姐8265434
相关分类