Python 无法从文件中排序数据

Python 无法从文件中排序数据,python,file,loops,Python,File,Loops,我正在打开并读取一个.txt文件,并试图以0.x或0.xy或0.xyz格式保存值 x必须是数字1-9 y不能是0或奇数 z不能是0或偶数 我当前的代码仅以0.x格式保存变量,但跳过了0.xy和0.xyz格式 For text file包含16000个元素,并包含整数、浮点和字符串: .03243234 234.234 .223 0.2 MWFE 等等 我的坏人。在阅读该行后忘记\n剥离。我添加了strip方法并为此调整了字符串 line = data.rstrip("\n") 生成的代码: l

我正在打开并读取一个.txt文件,并试图以0.x或0.xy或0.xyz格式保存值

x必须是数字1-9

y不能是0或奇数

z不能是0或偶数

我当前的代码仅以0.x格式保存变量,但跳过了0.xy和0.xyz格式

For text file包含16000个元素,并包含整数、浮点和字符串:

.03243234

234.234

.223

0.2

MWFE

等等


我的坏人。在阅读该行后忘记\n剥离。我添加了strip方法并为此调整了字符串

line = data.rstrip("\n")
生成的代码:

list = []

with open("exam2data.txt") as f:
    for data in f:
        data = f.readline()
        xCounter = 0
        yCounter = 0
        zCounter = 0
        line = data.rstrip("\n")
        try:
            lineFloat = float(line)
            if lineFloat < 1:
                if len(line) == 3:
                    if line[2] == 0:
                        pass
                    else:
                        list.append(lineFloat)
                        xCounter += 1

                elif len(line) == 4:
                    if line[3] == 0:
                        pass
                    else:
                        if line[2] == 0:
                            pass
                        else:
                            y = float(line[3])
                            if (y % 2 == 0):
                                list.append(lineFloat)
                                yCounter += 1
                            else:
                                pass

                elif len(line) == 5:
                     if line[4] == 0:
                        pass
                     else:
                        if line[3] == 0:
                            pass
                        else:
                            if line[2] == 0:
                                pass
                            else:
                                y = float(line[3])
                                z = float(line[4])
                                if (y % 2 == 0):
                                    if (z % 2 == 1):
                                        list.append(lineFloat)
                                        zCounter += 1
                                    else:
                                        pass
                                else:
                                    pass


        except:
            pass

print(len(list))
print(', '.join(map(str, list)))

你的问题应该问得更好。例如,当数字没有z时会发生什么。x必须是数字,但文件中有字符串吗?一些示例输入和预期输出会有所帮助。如果我理解了这个问题,下面的方法应该有效。我更喜欢用数学来分离数字,但这是我个人的偏好。请注意,我添加了一个测试,用于测试等于或小于零的数字。您永远不能信任文件IMHO的内容

def test_xyz(num_in):
    x, remain_x=divmod(num_in*10, 1)
    print "test_xyz", num_in, 
    if (1 <= x <= 9):
        print "good x", x
    else:
        print "Bad x" , x
        return

    if remain_x > 0:
        y, remain_y=divmod(remain_x*10, 1)
        if (y != 0) and (y%2 == 0):
            print "good y"
        else:
            print "Bad y", y
            return

        if remain_y > 0:
            z, remain_z=divmod(remain_y*10, 1)
            if (z != 0) and (z%2 != 0):
                print "good z"
            else:
                print "Bad z", z
    return

##-----------------------------------------------------------
test_data=""".223
0.2
1.234
0.23456
0.023
0.101"""

recs=test_data.split("\n")
for rec in recs:
    rec=float(rec)
    print "\n number", rec
    if rec < 1 and rec > 0:
        test_xyz(rec)
    else:
        print "number >= 1"

这里有一种文本匹配方法。我将每个搜索模式分解为自己的函数,并引入了一个装饰器来跟踪结果

每个匹配函数在成功时返回字符串,在失败时返回None。函数是互斥的,最多一个函数可以成功,因此我可以安全地将结果合并为或不合并,或文本给出文本

def test_xyz(num_in):
    x, remain_x=divmod(num_in*10, 1)
    print "test_xyz", num_in, 
    if (1 <= x <= 9):
        print "good x", x
    else:
        print "Bad x" , x
        return

    if remain_x > 0:
        y, remain_y=divmod(remain_x*10, 1)
        if (y != 0) and (y%2 == 0):
            print "good y"
        else:
            print "Bad y", y
            return

        if remain_y > 0:
            z, remain_z=divmod(remain_y*10, 1)
            if (z != 0) and (z%2 != 0):
                print "good z"
            else:
                print "Bad z", z
    return

##-----------------------------------------------------------
test_data=""".223
0.2
1.234
0.23456
0.023
0.101"""

recs=test_data.split("\n")
for rec in recs:
    rec=float(rec)
    print "\n number", rec
    if rec < 1 and rec > 0:
        test_xyz(rec)
    else:
        print "number >= 1"
INFILE = "exam2data.txt"
XS = set("123456789")
YS = set("2468")
ZS = set("13579")

def count_not_none(fn):
    """
    A decorator which counts the number of times the wrapped
      function returns a value other than None
    """
    def wrapped_fn(s):
        result = fn(s)
        if result is not None:
            wrapped_fn.count += 1
        return result
    wrapped_fn.count = 0
    return wrapped_fn

@count_not_none
def match_x(line):
    if len(line) == 3 and line[:2] == "0." and line[2] in XS:
        return line
    else:
        return None

@count_not_none
def match_xy(line):
    if len(line) == 4 and line[:2] == "0." and line[2] in XS and line[3] in YS:
        return line
    else:
        return None

@count_not_none
def match_xyz(line):
    if len(line) == 5 and line[:2] == "0." and line[2] in XS and line[3] in YS and line[4] in ZS:
        return line
    else:
        return None

def main():
    # search for matching lines
    matches = []
    with open(INFILE) as inf:
        for line in inf:
            line = line.strip()
            result = match_x(line) or match_xy(line) or match_xyz(line)
            if result is not None:
                matches.append(line)
    # report on the results
    print("Matched 0.x   {} times".format(match_x.count))
    print("Matched 0.xy  {} times".format(match_xy.count))
    print("Matched 0.xyz {} times".format(match_xyz.count))
    print("{} matches found".format(len(matches)))
    print(", ".join(matches))

if __name__=="__main__":
    main()