@@ -65,8 +65,31 @@ def __init__(self, column, row, value, message):
65
65
self .message = message
66
66
67
67
68
+ def convert_boolean (string_value ):
69
+ """Converts a string to a boolean (see CONVERTERS).
70
+ There is a converter function for each column type.
71
+
72
+ Boolean strings are independent of case. Values interpreted as True
73
+ are: "yes", "true", "on", "1". values interpreted as False are
74
+ "no", "false", "off", "0". Any other value will result in a ValueError.
75
+
76
+ :param string_value: The string to convert
77
+
78
+ :raises: ValueError if the string cannot be represented by a boolean
79
+ """
80
+
81
+ lean_string_value = string_value .strip ().lower ()
82
+ if lean_string_value in ['yes' , 'true' , 'on' , '1' ]:
83
+ return True
84
+ elif lean_string_value in ['no' , 'false' , 'off' , '0' ]:
85
+ return False
86
+
87
+ # Not recognised boolean if we get here
88
+ raise ValueError ('Unrecognised boolean ({})' .format (lean_string_value ))
89
+
90
+
68
91
def convert_int (string_value ):
69
- """Converts a string to integer (see CONVERTERS).
92
+ """Converts a string to to an integer (see CONVERTERS).
70
93
There is a converter function for each column type.
71
94
72
95
:param string_value: The string to convert
@@ -77,7 +100,7 @@ def convert_int(string_value):
77
100
78
101
79
102
def convert_float (string_value ):
80
- """Converts string to float (see CONVERTERS).
103
+ """Converts string to a float (see CONVERTERS).
81
104
There is a converter function for each column type.
82
105
83
106
:param string_value: The string to convert
@@ -98,7 +121,8 @@ def convert_string(string_value):
98
121
99
122
# A map of column type names (case-insensitive) to string conversion function.
100
123
# If a column is 'name:INT' then we call 'convert_int()' for the column values.
101
- CONVERTERS = {'int' : convert_int ,
124
+ CONVERTERS = {'boolean' : convert_boolean ,
125
+ 'int' : convert_int ,
102
126
'float' : convert_float ,
103
127
'string' : convert_string }
104
128
@@ -114,7 +138,8 @@ class TypedColumnReader(object):
114
138
where, if the column header defines a type, the value is converted to that
115
139
type.
116
140
117
- There is built-in support for ``int``, ``float`` and ``string`` data types.
141
+ There is built-in support for ``boolean``,
142
+ ``int``, ``float`` and ``string`` data types.
118
143
119
144
As an example, the following is a comma-separated header for a file with
120
145
columns ``names`` "smiles", "comment", "hac" and "ratio" where
@@ -128,7 +153,6 @@ class TypedColumnReader(object):
128
153
* If a column value is empty/blank the corresponding dictionary
129
154
value is ``None``
130
155
131
-
132
156
"""
133
157
134
158
def __init__ (self , csv_file ,
0 commit comments