在排序文件中的数据时遇到问题
问题描述:
我正在打开并读取.txt文件,并试图以0.x或0.xy或0.xyz格式保存值。在排序文件中的数据时遇到问题
x必须是数字1-9
Y不能是0或一个奇数
Z不能是0或偶数
我的当前代码只保存在该变量格式为0.x,但跳过了0.xy和0.xyz。
对于文本文件有16000元,并包含整数,浮点数和字符串:
0.03243234
234.234
0.223
0.2
MWFE
等
list = []
with open("exam2data.txt") as f:
for line in f:
line = f.readline()
xCounter = 0
yCounter = 0
zCounter = 0
try:
lineFloat = float(line)
if lineFloat < 1:
if len(line) == 4:
if line[3] == 0:
pass
else:
list.append(lineFloat)
xCounter += 1
elif len(line) == 5:
if line[3] == 0:
pass
else:
if line[2] == 0:
pass
else:
y = float(line[4])
if (y % 2 == 0):
list.append(lineFloat)
yCounter += 1
else:
pass
elif len(line) == 6:
if line[4] == 0:
pass
else:
if line[5] == 0:
pass
else:
if line[3] == 0:
pass
else:
y = float(line[4])
z = float(line[5])
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)))
答
我的坏人。在阅读完该行后忘记删除\ 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必须是数字,但文件中有字符串?一些示例输入和预期输出将有所帮助。如果我理解了这个问题,那么下面的内容应该可行我更喜欢用数学来隔离数字,但这是个人偏好。并且请注意,我为等于或小于零的数字添加了一个测试。你永远不能相信文件恕我直言的内容。
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。这些功能是相互排斥的(最多可以成功),因此我可以安全地将结果与or
(None or "text"
给出"text"
)合并。
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()