Vous avez reçu un message "Your GitLab account has been locked ..." ? Pas d'inquiétude : lisez cet article https://docs.gricad-pages.univ-grenoble-alpes.fr/help/unlock/

Commit 264743e4 authored by Franck Thollard's avatar Franck Thollard
Browse files

adding a example function with regex and logging

parent 6b8b17a6
......@@ -4,6 +4,9 @@ form key=val where key is p1, p2 or p3, and val is a float.
"""
import re
import logging
logging.basicConfig(level=logging.INFO)
def compute_stats(file_name):
"""
......@@ -26,6 +29,40 @@ def compute_stats(file_name):
return (number, total_sum, total_sum/float(number))
def check_format_re(file_name, default_values):
"""Check the file has the right format
:param file_name: (str) the input file name (text)
:param default_values: (array of float) the default values for
p1, p2, and p3 respectivelly
:returns: the read values
"""
with open(file_name) as handle:
for line_num, line in enumerate(handle):
vals = [None, None, None]
logging.debug("line = {}".format(line.strip()))
for si, sv in re.findall(r"p(\d)\s*=\s*(\d\.\d+)", line):
try:
idx = int(si) - 1
except ValueError as e:
logging.warning(f'file {file_name} line {line_num}: wrong format: p{si}')
continue
if idx > 2:
logging.warning(f'file {file_name} line {line_num}: p{si} out of bounds')
continue
try:
val = float(sv)
except ValueError as e:
logging.warning(f'file {file_name} line {line_num}: wrong value: p{si}')
continue
vals[idx] = val
# checking for missing item
for i,v in enumerate(vals):
if v is None:
logging.warning(f'file {file_name} line {line_num}: missing: p{i+1}, setting default value')
vals[i] = default_values[i-1]
def check_format(file_name, cols_names_set):
"""
check the file has the right format.
......@@ -68,3 +105,8 @@ sums = []
for file_name in file_names:
check_format(file_name, cols_names_set)
# using version with re, and type check
print("USING VERSION WITH RE AND TYPE CHECK")
for file_name in file_names:
check_format_re(file_name, [100, 200, 300])
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment