识别逗号之间的空格

时间:2019-06-17 20:50:10

标签: python python-3.x

我需要确定数字和逗号之间是否有空格,然后该数字无效。因此,如果该数字在逗号之间具有多于或少于2个小数位和/或空格,则它是无效的;但是如果在逗号之间没有空格且具有2个小数位,则它是一个有效的数字。这就是第一行的第一个数字有效的原因

有两种方法,我更喜欢使用方法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:
    for line in file:
        index = index + 1
        o = "Line {}: ".format(index)
        number_list = line.strip().split(',')
        for x in number_list:
            if len(x.split('.')[-1]) == 2:
                o += valid_string + " "
            if len(x.split('.')[-1]) != 2:
                o += invalid_string + " "
            if len(x.split(',')[-1]) == " ":
                o += valid_string + " "

这是我在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

4 个答案:

答案 0 :(得分:1)

您可以使用,拆分字符串,并根据字符串是否以空格开头来决定该字符串有效还是无效

#Open the files
with 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 INVALID
Line 2: VALID INVALID INVALID

答案 1 :(得分:1)

尝试一下:

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)

从文件读取:

nbline

with 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行:有效无效

答案 2 :(得分:0)

使用decimal.Decimal对象,您可以检索指数,该指数以某种方式告诉您小数位数(see docs):

import decimal
o += " ".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'

答案 3 :(得分:0)

基于逗号分隔的列表理解和一些字符串欺骗将更加简单:

line="1,1.02, 123.0005"
result = " ".join("IN"*(" " in s)+"VALID" for s in line.split(","))
print(result) # VALID VALID INVALID