识别逗号之间的空格

我需要确定数字和逗号之间是否有空格,那么该数字无效。因此,如果数字在逗号之间有超过或少于 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


尚方宝剑之说
浏览 178回答 3
3回答

潇潇雨雨

您可以拆分字符串,并根据字符串是否带有空格来确定字符串是有效还是无效#Open the fileswith open('file.txt') as fp:    #Extract out non-empty lines from file    lines = [line for line in fp.readlines() if line.strip()]    res = []    #Iterate over the lines    for idx, line in enumerate(lines):        #Number is valid if it doesn't start with a whitespace, has a decimal part and the decimal part is two digits long        res = ['VALID' if not item.startswith(' ') and '.' in item and len(item.split('.')[1]) == 2 else 'INVALID' for item in line.split(',')]        #Print the result        print("Line {}: {}".format(idx+1, ' '.join(res)))输出将是Line 1: INVALID VALID INVALIDLine 2: VALID INVALID INVALID

桃花长相依

尝试这个:line="1,1.02, 123.0005"reslt=line.split(",")Res=" "for i in reslt:    if " "in i:        line1="INVALID "    else:        line1="VALID "    Res +="".join(line1)print("line1:"+Res)从文件中读取:nblinewith open('file.txt') as f:    for line in f.readlines():        print(line)        reslt=line.split(",")        Res=" "        for i in reslt:            if " "in i:                line1="INVALID "            else:                line1="VALID "            Res +="".join(line1)    nbline = nbline+1    print("line {}:{}".format(nbline,Res))输出:第 1 行:有效有效无效

慕姐8265434

使用decimal.Decimal对象,您可以检索指数,它以某种方式告诉您小数位数(请参阅文档):import decimalo += " ".join(['INVALID' if x[0] == ' ' or decimal.Decimal(x).as_tuple().exponent != -2 else 'VALID' for x in line.split(',')])输出#with line = "1,1.02, 123.0005"'Line 1: INVALID VALID INVALID'#with line = "1.02, 1.02 , 1.02"'Line 2: VALID INVALID INVALID'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python