繁体   English   中英

识别逗号之间的空格

[英]Identifying spaces between commas

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

您可以使用分割字符串,并根据字符串是否以空格加星号来确定该字符串有效还是无效

#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

尝试这个:

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))

输出:line1:VALID VALID INVALID

使用decimal.Decimal对象,您可以检索指数,该指数以某种方式告诉您小数位数( 请参阅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'

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM