imcflibs.strtools
String related helper functions.
1"""String related helper functions.""" 2 3import re 4 5 6# this is taken from numpy's iotools: 7def _is_string_like(obj): 8 """Check whether obj behaves like a string. 9 10 Using this way of checking for a string-like object is more robust when 11 dealing with stuff that can behave like a 'str' but is not strictly an 12 instance of it (or a subclass thereof). So it's more generic than using 13 isinstance(obj, str). 14 15 Example 16 ------- 17 >>> _is_string_like('foo') 18 True 19 >>> _is_string_like(123) 20 False 21 """ 22 try: 23 obj + "" 24 except (TypeError, ValueError): 25 return False 26 return True 27 28 29def filename(name): 30 """Get the filename from either a filehandle or a string. 31 32 This is a convenience function to retrieve the filename as a string given 33 either an open filehandle or just a plain str containing the name. 34 35 When running in Jython the function will also convert `java.io.File` objects 36 to `str`. NOTE: this also works if the Java object is a directory, not an 37 actual file. 38 39 Parameters 40 ---------- 41 name : str or filehandle or java.io.File 42 43 Returns 44 ------- 45 name : str 46 47 Example 48 ------- 49 >>> filename('test_file_name') 50 'test_file_name' 51 52 >>> import os.path 53 >>> fname = filename(open(__file__, 'r')) 54 >>> os.path.basename(fname) in ['strtools.py', 'strtools.pyc'] 55 True 56 """ 57 try: 58 if isinstance(name, java.io.File): 59 return str(name) 60 except: 61 # we silently ignore this case and continue with checks below as most 62 # likely we are not running under Jython 63 pass 64 65 if isinstance(name, file): 66 return name.name 67 elif _is_string_like(name): 68 return name 69 else: 70 raise TypeError 71 72 73def flatten(lst): 74 """Make a single string from a list of strings. 75 76 Parameters 77 ---------- 78 lst : list(str) 79 80 Returns 81 ------- 82 flat : str 83 84 Example 85 ------- 86 >>> flatten(('foo', 'bar')) 87 'foobar' 88 """ 89 flat = "" 90 for line in lst: 91 flat += line 92 return flat 93 94 95def strip_prefix(string, prefix): 96 """Remove a given prefix from a string. 97 98 Parameters 99 ---------- 100 string : str 101 The original string from which the prefix should be removed. 102 prefix : str 103 The prefix to be removed. 104 105 Returns 106 ------- 107 str 108 The original string without the given prefix. In case the original 109 string doesn't start with the prefix, it is returned unchanged. 110 """ 111 if string.startswith(prefix): 112 string = string[len(prefix) :] 113 return string 114 115 116def sort_alphanumerically(data): 117 """Sort a list alphanumerically. 118 119 Parameters 120 ---------- 121 data : list 122 List containing all the files to sort. 123 124 Returns 125 ------- 126 list 127 List with filenames sorted. 128 129 Examples 130 -------- 131 >>> sorted([ "foo-1", "foo-2", "foo-10" ]) 132 ["foo-1", "foo-10", "foo-2"] 133 134 >>> sort_alphanumerically([ "foo-1", "foo-2", "foo-10" ]) 135 ["foo-1", "foo-2", "foo-10"] 136 """ 137 convert = lambda text: int(text) if text.isdigit() else text.lower() 138 alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)] 139 return sorted(data, key=alphanum_key)
def
filename(name):
30def filename(name): 31 """Get the filename from either a filehandle or a string. 32 33 This is a convenience function to retrieve the filename as a string given 34 either an open filehandle or just a plain str containing the name. 35 36 When running in Jython the function will also convert `java.io.File` objects 37 to `str`. NOTE: this also works if the Java object is a directory, not an 38 actual file. 39 40 Parameters 41 ---------- 42 name : str or filehandle or java.io.File 43 44 Returns 45 ------- 46 name : str 47 48 Example 49 ------- 50 >>> filename('test_file_name') 51 'test_file_name' 52 53 >>> import os.path 54 >>> fname = filename(open(__file__, 'r')) 55 >>> os.path.basename(fname) in ['strtools.py', 'strtools.pyc'] 56 True 57 """ 58 try: 59 if isinstance(name, java.io.File): 60 return str(name) 61 except: 62 # we silently ignore this case and continue with checks below as most 63 # likely we are not running under Jython 64 pass 65 66 if isinstance(name, file): 67 return name.name 68 elif _is_string_like(name): 69 return name 70 else: 71 raise TypeError
Get the filename from either a filehandle or a string.
This is a convenience function to retrieve the filename as a string given either an open filehandle or just a plain str containing the name.
When running in Jython the function will also convert java.io.File
objects
to str
. NOTE: this also works if the Java object is a directory, not an
actual file.
Parameters
- name (str or filehandle or java.io.File):
Returns
- name (str):
Example
>>> filename('test_file_name')
'test_file_name'
>>> import os.path
>>> fname = filename(open(__file__, 'r'))
>>> os.path.basename(fname) in ['strtools.py', 'strtools.pyc']
True
def
flatten(lst):
74def flatten(lst): 75 """Make a single string from a list of strings. 76 77 Parameters 78 ---------- 79 lst : list(str) 80 81 Returns 82 ------- 83 flat : str 84 85 Example 86 ------- 87 >>> flatten(('foo', 'bar')) 88 'foobar' 89 """ 90 flat = "" 91 for line in lst: 92 flat += line 93 return flat
Make a single string from a list of strings.
Parameters
- lst (list(str)):
Returns
- flat (str):
Example
>>> flatten(('foo', 'bar'))
'foobar'
def
strip_prefix(string, prefix):
96def strip_prefix(string, prefix): 97 """Remove a given prefix from a string. 98 99 Parameters 100 ---------- 101 string : str 102 The original string from which the prefix should be removed. 103 prefix : str 104 The prefix to be removed. 105 106 Returns 107 ------- 108 str 109 The original string without the given prefix. In case the original 110 string doesn't start with the prefix, it is returned unchanged. 111 """ 112 if string.startswith(prefix): 113 string = string[len(prefix) :] 114 return string
Remove a given prefix from a string.
Parameters
- string (str): The original string from which the prefix should be removed.
- prefix (str): The prefix to be removed.
Returns
- str: The original string without the given prefix. In case the original string doesn't start with the prefix, it is returned unchanged.
def
sort_alphanumerically(data):
117def sort_alphanumerically(data): 118 """Sort a list alphanumerically. 119 120 Parameters 121 ---------- 122 data : list 123 List containing all the files to sort. 124 125 Returns 126 ------- 127 list 128 List with filenames sorted. 129 130 Examples 131 -------- 132 >>> sorted([ "foo-1", "foo-2", "foo-10" ]) 133 ["foo-1", "foo-10", "foo-2"] 134 135 >>> sort_alphanumerically([ "foo-1", "foo-2", "foo-10" ]) 136 ["foo-1", "foo-2", "foo-10"] 137 """ 138 convert = lambda text: int(text) if text.isdigit() else text.lower() 139 alphanum_key = lambda key: [convert(c) for c in re.split("([0-9]+)", key)] 140 return sorted(data, key=alphanum_key)
Sort a list alphanumerically.
Parameters
- data (list): List containing all the files to sort.
Returns
- list: List with filenames sorted.
Examples
>>> sorted([ "foo-1", "foo-2", "foo-10" ])
["foo-1", "foo-10", "foo-2"]
>>> sort_alphanumerically([ "foo-1", "foo-2", "foo-10" ])
["foo-1", "foo-2", "foo-10"]