summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSylvain Th?nault <sylvain.thenault@logilab.fr>2010-08-09 11:46:58 +0200
committerSylvain Th?nault <sylvain.thenault@logilab.fr>2010-08-09 11:46:58 +0200
commita2effd103e2f0c76f317166d97d2efa32c74b654 (patch)
treed935fa58f179ec6493dc4e0f543cb85de5ee9779
parent38076ce0a97e1274f4ce47bed336c34c026a7a28 (diff)
downloadlogilab-common-a2effd103e2f0c76f317166d97d2efa32c74b654.tar.gz
new text_to_dict function
-rw-r--r--textutils.py36
1 files changed, 32 insertions, 4 deletions
diff --git a/textutils.py b/textutils.py
index a01c733..16926f0 100644
--- a/textutils.py
+++ b/textutils.py
@@ -18,10 +18,6 @@
"""Some text manipulation utility functions.
-
-
-
-
:group text formatting: normalize_text, normalize_paragraph, pretty_match,\
unquote, colorize_ansi
:group text manipulation: searchall, splitstrip
@@ -211,6 +207,7 @@ def normalize_rest_paragraph(text, line_len=80, indent=''):
lines.append(indent + line.strip())
return linesep.join(lines)
+
def splittext(text, line_len):
"""split the given text on space according to the given max line size
@@ -253,6 +250,36 @@ def splitstrip(string, sep=','):
get_csv = deprecated()(splitstrip)
+
+def text_to_dict(text):
+ """parse multilines text containing simple 'key=value' lines and return a
+ dict of {'key': 'value'}. When the same key is encountered multiple time,
+ value is turned into a list containing all values.
+
+ >>> text_to_dict('''multiple=1
+ ... multiple= 2
+ ... single =3
+ ... ''')
+ {'single': '3', 'multiple': ['1', '2']}
+
+ """
+ res = {}
+ if not text:
+ return res
+ for line in text.splitlines():
+ line = line.strip()
+ if line:
+ key, value = [w.strip() for w in line.split('=', 1)]
+ if key in res:
+ try:
+ res[key].append(value)
+ except AttributeError:
+ res[key] = [res[key], value]
+ else:
+ res[key] = value
+ return res
+
+
_BLANK_URE = r'(\s|,)+'
_BLANK_RE = re.compile(_BLANK_URE)
__VALUE_URE = r'-?(([0-9]+\.[0-9]*)|((0x?)?[0-9]+))'
@@ -314,6 +341,7 @@ def apply_units( string, units, inter=None, final=float, blank_reg=_BLANK_RE,
values.append(value)
return final(sum(values))
+
_LINE_RGX = re.compile('\r\n|\r+|\n')
def pretty_match(match, string, underline_char='^'):