我必须编写一个从文本文件中检索数据然后读取这些数字的函数。所以我想我需要一个循环来做到这一点,到目前为止我有:
f= "textfile.txt"
while f.readline() != "": #while line is not empty do:
文本文件中的数据就像这样:
3,2,4,1
1,,4,2
13,2,16,3
etc...
所以我已经读过这些数据,并且如果数据与上述数据不正确,则进行错误检测。所以不需要3个数字,因为“1,4”中的空白点将被0替换为“1,0,4”
数据更正将如下:
14,3,,2 will become 14,3,0,2
,,4, will become 0,0,4,0
1,2,3,4,5 will become [] (empty as there are too many numbers)
,,,, will become [] (empty as there are no numbers)
0,0,0,0 will become [] (empty as there is'nt at least one number > 0 )
3,2,-7,8 will become [] (empty as there is a negative number)
3,2,7.3,8 will become [] (empty as there is a float)
基本上,只允许空格或正面整数。
我对此的基本理解是你需要使用split函数来单独获取数字,然后进行错误检测。我已经有另一个函数可以对单个数字进行基本的错误检测
def detect(s)
if s == "" :
return 0
if s < 0 :
return -1
if s > 0 :
return s
帮助将非常感谢。 提前谢谢
答案 0 :(得分:1)
您可以对分割数据使用列表理解:
data='1,,4,2'
result=[int(d) if d else 0 for d in data.split(',')]
print result
输出:
[1, 0, 4, 2]
您可以在每一行上执行此操作。
答案 1 :(得分:0)
请注意:在某些IDE中(例如spyder)
all()
函数有奇怪的行为,因此此代码无法在终端或IPython中尝试
这是一项非常艰巨的任务,只需一步,这是我的解决方案:
with open(r'/Desktop/text.txt') as f:
...: for i in filter(None, (line.rstrip() for line in f)):
...: if all(c in '0,' for c in i):
...: print []
...: elif '.' not in i and '-' not in i:
...: print [int(d) if d else 0 for d in i.split(',')]
...: else:
...: print []
输入:
14,3,,2
,,4,
1,2,3,4,5
,,,,
0,0,0,0
3,2,-7,8
3,2,7.3,8
3,2,4.5,2
1,2,2,2,
0,0,0,0,0
输出:
[14, 3, 0, 2]
[0, 0, 4, 0]
[1, 2, 3, 4, 5]
[]
[]
[]
[]
[]
[1, 2, 2, 2, 0]
[]