Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
python-uga
py-training-2017
Commits
264743e4
Commit
264743e4
authored
Mar 11, 2019
by
Franck Thollard
Browse files
adding a example function with regex and logging
parent
6b8b17a6
Changes
1
Hide whitespace changes
Inline
Side-by-side
TP/TP0_file_stats/corrections/step2.0.py
View file @
264743e4
...
...
@@ -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
])
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment