1 |
73
|
aaronmk
|
# String manipulation
|
2 |
|
|
|
3 |
1295
|
aaronmk
|
import codecs
|
4 |
861
|
aaronmk
|
import re
|
5 |
|
|
|
6 |
1232
|
aaronmk
|
import util
|
7 |
|
|
|
8 |
1295
|
aaronmk
|
unicode_reader = codecs.getreader('utf_8')
|
9 |
|
|
|
10 |
73
|
aaronmk
|
def to_unicode(str_):
|
11 |
|
|
if isinstance(str_, unicode): return str_
|
12 |
|
|
encodings = ['utf_8', 'latin_1']
|
13 |
|
|
for encoding in encodings:
|
14 |
|
|
try: return unicode(str_, encoding)
|
15 |
|
|
except UnicodeDecodeError, e: pass
|
16 |
|
|
raise AssertionError(encoding+' is not a catch-all encoding')
|
17 |
340
|
aaronmk
|
|
18 |
1232
|
aaronmk
|
def ustr(val):
|
19 |
|
|
'''Like built-in str() but converts to unicode object'''
|
20 |
|
|
if not util.is_str(val): val = str(val)
|
21 |
|
|
return to_unicode(val)
|
22 |
|
|
|
23 |
340
|
aaronmk
|
def ensure_newl(str_): return str_.rstrip()+'\n'
|
24 |
714
|
aaronmk
|
|
25 |
856
|
aaronmk
|
def is_multiline(str_):
|
26 |
|
|
newl_idx = str_.find('\n')
|
27 |
|
|
return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
|
28 |
|
|
|
29 |
860
|
aaronmk
|
def remove_extra_newl(str_):
|
30 |
856
|
aaronmk
|
if is_multiline(str_): return str_
|
31 |
|
|
else: return str_.rstrip()
|
32 |
|
|
|
33 |
714
|
aaronmk
|
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
|
34 |
|
|
|
35 |
|
|
def cleanup(str_): return std_newl(str_.strip())
|
36 |
861
|
aaronmk
|
|
37 |
1364
|
aaronmk
|
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
|
38 |
|
|
|
39 |
861
|
aaronmk
|
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
|