Project

General

Profile

1 73 aaronmk
# String manipulation
2
3 1295 aaronmk
import codecs
4 861 aaronmk
import re
5
6 1232 aaronmk
import util
7
8 2301 aaronmk
##### Debug printing
9
10
class DebugPrintable:
11
    def __str__(self): return util.class_name(self)+repr(self.__dict__)
12
13
    def __repr__(self): return str(self)
14
15 1622 aaronmk
##### Parsing
16
17
def split(sep, str_):
18
    '''Returns [] if str_ == ""'''
19
    if str_ == '': return []
20
    else: return str_.split(sep)
21
22 2221 aaronmk
def remove_prefix(prefix, str_, removed_ref=None):
23
    if removed_ref == None: removed_ref = [False]
24
25
    removed_ref[0] = str_.startswith(prefix)
26
    if removed_ref[0]: return str_[len(prefix):]
27 1622 aaronmk
    else: return str_
28
29 1680 aaronmk
def remove_prefixes(prefixes, str_):
30
    for prefix in prefixes: str_ = remove_prefix(prefix, str_)
31
    return str_
32
33
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
34
35 2221 aaronmk
def remove_suffix(suffix, str_, removed_ref=None):
36
    if removed_ref == None: removed_ref = [False]
37
38
    removed_ref[0] = str_.endswith(suffix)
39
    if removed_ref[0]: return str_[:-len(suffix)]
40 1622 aaronmk
    else: return str_
41
42 1959 aaronmk
def contains_any(haystack, needles):
43
    for needle in needles:
44
        if haystack.find(needle) >= 0: return True
45
    return False
46
47 1622 aaronmk
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
48
49 1401 aaronmk
##### Unicode
50
51 1295 aaronmk
unicode_reader = codecs.getreader('utf_8')
52
53 73 aaronmk
def to_unicode(str_):
54
    if isinstance(str_, unicode): return str_
55
    encodings = ['utf_8', 'latin_1']
56
    for encoding in encodings:
57
        try: return unicode(str_, encoding)
58
        except UnicodeDecodeError, e: pass
59
    raise AssertionError(encoding+' is not a catch-all encoding')
60 340 aaronmk
61 1232 aaronmk
def ustr(val):
62
    '''Like built-in str() but converts to unicode object'''
63
    if not util.is_str(val): val = str(val)
64
    return to_unicode(val)
65
66 1401 aaronmk
##### Line endings
67
68 1622 aaronmk
def extract_line_ending(line):
69
    '''@return tuple (contents, ending)'''
70
    contents = remove_suffix('\r', remove_suffix('\n', line))
71
    return (contents, line[len(contents):])
72 714 aaronmk
73 1622 aaronmk
def remove_line_ending(line): return extract_line_ending(line)[0]
74
75
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
76
77 856 aaronmk
def is_multiline(str_):
78
    newl_idx = str_.find('\n')
79
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
80
81 860 aaronmk
def remove_extra_newl(str_):
82 856 aaronmk
    if is_multiline(str_): return str_
83
    else: return str_.rstrip()
84
85 714 aaronmk
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
86
87 1401 aaronmk
##### Whitespace
88
89 714 aaronmk
def cleanup(str_): return std_newl(str_.strip())
90 861 aaronmk
91 1364 aaronmk
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
92
93 861 aaronmk
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
94 1761 aaronmk
95
##### Control characters
96
97
def is_ctrl(char):
98
    '''Whether char is a (non-printable) control character'''
99
    return ord(char) < 32 and not char.isspace()
100
101
def strip_ctrl(str_):
102
    '''Strips (non-printable) control characters'''
103
    return ''.join(filter(lambda c: not is_ctrl(c), str_))