我有一个用逗号分隔的数字列表,我想要输出或者我希望它返回文本文件每一行中每个数字的小数位数,并且我还希望它说“找到空白”在该行中,如果数字和逗号之间有空格,如果没有,我要说“未发现错误”。我检查了代码是否有大于或小于两个小数位和/或之间有空格数字则无效。
如果没有空格并且它有两个小数位,则它是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)))
为该行中读取的每个数字返回小数位数,并用制表符将它们分开。另外,如果数字和逗号之间有空格,则返回空格,如果没有空格,则不返回错误
以文本文件为例
1.1,1.023, 1.45
1.1,1.023,1.45
预期:
返回
Line 1: 1”tab”3”tab”2”tab”white space found
Line 2: 1”tab”3”tab”2”tab”no error found
答案 0 :(得分:1)
file.txt
包含:
1.1,1.023, 1.45
1.1,1.023,1.45
脚本:
import re
with open('file.txt', 'r') as f_in:
line_no = 1
for line in f_in:
if not line.strip():
continue
print('Line {}:'.format(line_no), end=' ')
print('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line) ), end='\t')
print('white space found' if re.findall(r',(\s+)\d', line) else 'no error found')
line_no += 1
打印:
Line 1: 1 3 2 white space found
Line 2: 1 3 2 no error found