Python string.split() Examples
The following are 30
code examples of string.split().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
string
, or try the search function
.
Example #1
Source File: bdist_rpm.py From ironpython2 with Apache License 2.0 | 6 votes |
def _format_changelog(self, changelog): """Format the changelog correctly and convert it to a list of strings """ if not changelog: return changelog new_changelog = [] for line in string.split(string.strip(changelog), '\n'): line = string.strip(line) if line[0] == '*': new_changelog.extend(['', line]) elif line[0] == '-': new_changelog.append(line) else: new_changelog.append(' ' + line) # strip trailing newline inserted by first changelog entry if not new_changelog[0]: del new_changelog[0] return new_changelog # _format_changelog() # class bdist_rpm
Example #2
Source File: wordnet.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def _initializePOSTables(): global _POSNormalizationTable, _POStoDictionaryTable _POSNormalizationTable = {} _POStoDictionaryTable = {} for pos, abbreviations in ( (NOUN, "noun n n."), (VERB, "verb v v."), (ADJECTIVE, "adjective adj adj. a s"), (ADVERB, "adverb adv adv. r")): tokens = string.split(abbreviations) for token in tokens: _POSNormalizationTable[token] = pos _POSNormalizationTable[string.upper(token)] = pos for dict in Dictionaries: _POSNormalizationTable[dict] = dict.pos _POStoDictionaryTable[dict.pos] = dict
Example #3
Source File: toolbox.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def _parse_record(s): """ Deprecated: use C{StandardFormat.fields()} @param s: toolbox record as a string @type s: L{string} @rtype: iterator over L{list(string)} """ s = "\n" + s # Fields (even first) must start w/ a carriage return if s.endswith("\n") : s = s[:-1] # Remove single extra carriage return for field in split(s, sep="\n\\")[1:] : # Parse by carriage return followed by backslash parsed_field = split(field, sep=" ", maxsplit=1) # Split properly delineated field try : yield (parsed_field[0], parsed_field[1]) except IndexError : yield (parsed_field[0], '')
Example #4
Source File: cxml.py From yang-explorer with Apache License 2.0 | 6 votes |
def type_identityref_values(self, t): base_idn = t.search_one('base') if base_idn: # identity has a base idn_key = None base_idns = base_idn.arg.split(':') if len(base_idns) > 1: for module in self.module_prefixes: if base_idns[0] == self.module_prefixes[module][0]: idn_key = module + ':' + base_idns[1] break else: idn_key = self.name + ':' + base_idn.arg if idn_key is None: return '' value_stmts = [] stmts = self.identity_deps.get(idn_key, []) for value in stmts: ids = value.split(':') value_stmts.append(self.module_prefixes[ids[0]][0] + ':' + ids[1]) if stmts: return '|'.join(sorted(value_stmts)) return ''
Example #5
Source File: __init__.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def _substitute(self, str): """ Substitute words in the string, according to the specified reflections, e.g. "I'm" -> "you are" @type str: C{string} @param str: The string to be mapped @rtype: C{string} """ words = "" for word in string.split(string.lower(str)): if self._reflections.has_key(word): word = self._reflections[word] words += ' ' + word return words
Example #6
Source File: wordnet.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def _initializePOSTables(): global _POSNormalizationTable, _POStoDictionaryTable _POSNormalizationTable = {} _POStoDictionaryTable = {} for pos, abbreviations in ( (NOUN, "noun n n."), (VERB, "verb v v."), (ADJECTIVE, "adjective adj adj. a s"), (ADVERB, "adverb adv adv. r")): tokens = string.split(abbreviations) for token in tokens: _POSNormalizationTable[token] = pos _POSNormalizationTable[string.upper(token)] = pos for dict in Dictionaries: _POSNormalizationTable[dict] = dict.pos _POStoDictionaryTable[dict.pos] = dict
Example #7
Source File: meica.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def version_checker(cur_ver,ref_ver): """ Checks version in major/minor format of a current version versus a reference version. Supports 2 or more level versioning, only 2 levels checked) Input: cur_ver: float or string of version to check ref_ver: float or string of reference version Returns: bool for pass or fail """ cur_ver = str(cur_ver) ref_ver = str(ref_ver) cur_Varr = [int(vvv) for vvv in cur_ver.split('.')[0:2]] cur_V = cur_Varr[0]*10**2 + cur_Varr[1]%100 ref_Varr = [int(vvv) for vvv in ref_ver.split('.')[0:2]] ref_V = ref_Varr[0]*10**2 + ref_Varr[1]%100 if cur_V > ref_V: return True return False #Run dependency check
Example #8
Source File: meica_gui.py From me-ica with GNU Lesser General Public License v2.1 | 6 votes |
def version_checker(cur_ver,ref_ver): """ Checks version in major/minor format of a current version versus a reference version. Supports 2 or more level versioning, only 2 levels checked) Input: cur_ver: float or string of version to check ref_ver: float or string of reference version Returns: bool for pass or fail """ cur_ver = str(cur_ver) ref_ver = str(ref_ver) cur_Varr = [int(vvv) for vvv in cur_ver.split('.')[0:2]] cur_V = cur_Varr[0]*10**2 + cur_Varr[1]%100 ref_Varr = [int(vvv) for vvv in ref_ver.split('.')[0:2]] ref_V = ref_Varr[0]*10**2 + ref_Varr[1]%100 if cur_V > ref_V: return True return False #Run dependency check
Example #9
Source File: visual_metrics.py From compare-codecs with Apache License 2.0 | 6 votes |
def ParseMetricFile(file_name, metric_column): """ Convert a metrics file into a set of numbers. This returns a sorted list of tuples with the first number being from the first column (bitrate) and the second being from metric_column (counting from 0). """ metric_set1 = set([]) metric_file = open(file_name, "r") for line in metric_file: metrics = string.split(line) if HasMetrics(line): if metric_column < len(metrics): my_tuple = float(metrics[0]), float(metrics[metric_column]) else: my_tuple = float(metrics[0]), 0 metric_set1.add(my_tuple) metric_set1_sorted = sorted(metric_set1) return metric_set1_sorted
Example #10
Source File: 1.py From Python-John-Zelle-book with MIT License | 6 votes |
def main(): print "This program converts a sequence of ASCII numbers into" print "the string of text that it represents." print inString = raw_input("Please enter the ASCII-encoded message: ") message = [] for numStr in string.split(inString): asciiNum = eval(numStr) message1 = ord(asciiNum) # convert digits to a number message.append(message1) print message print "The decoded message is:","".join(message)
Example #11
Source File: sigfig.py From magpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def round_sig_error(x, ex, n, paren=False): '''Find ex rounded to n sig-figs and make the floating point x match the number of decimals. If [paren], the string is returned as quantity(error) format''' stex = round_sig(ex,n) if stex.find('.') < 0: extra_zeros = len(stex) - n sigfigs = len(str(int(x))) - extra_zeros stx = round_sig(x,sigfigs) else: num_after_dec = len(string.split(stex,'.')[1]) stx = ("%%.%df" % num_after_dec) % (x) if paren: if stex.find('.') >= 0: stex = stex[stex.find('.')+1:] return "%s(%s)" % (stx,stex) return stx,stex
Example #12
Source File: sigfig.py From magpy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def round_sig_error2(x, ex1, ex2, n): '''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x and max(ex,ex2) match the number of decimals.''' minerr = min(ex1,ex2) minstex = round_sig(minerr,n) if minstex.find('.') < 0: extra_zeros = len(minstex) - n sigfigs = len(str(int(x))) - extra_zeros stx = round_sig(x,sigfigs) maxstex = round_sig(max(ex1,ex2),sigfigs) else: num_after_dec = len(string.split(minstex,'.')[1]) stx = ("%%.%df" % num_after_dec) % (x) maxstex = ("%%.%df" % num_after_dec) % (max(ex1,ex2)) if ex1 < ex2: return stx,minstex,maxstex else: return stx,maxstex,minstex
Example #13
Source File: mac_shadow.py From salt-osx with MIT License | 6 votes |
def _extract_authdata(item): ''' Extract version, authority tag, and authority data from a single array item of AuthenticationAuthority item The NSString instance representing the authority string returns version (default 1.0.0), tag, data as a tuple ''' parts = string.split(item, ';', 2) if not parts[0]: parts[0] = '1.0.0' return { 'version': parts[0], 'tag': parts[1], 'data': parts[2] }
Example #14
Source File: msvccompiler.py From meddle with MIT License | 6 votes |
def find_exe(self, exe): """Return path to an MSVC executable program. Tries to find the program in several places: first, one of the MSVC program search paths from the registry; next, the directories in the PATH environment variable. If any of those work, return an absolute path that is known to exist. If none of them work, just return the original program name, 'exe'. """ for p in self.__paths: fn = os.path.join(os.path.abspath(p), exe) if os.path.isfile(fn): return fn # didn't find it; try existing path for p in string.split(os.environ['Path'],';'): fn = os.path.join(os.path.abspath(p),exe) if os.path.isfile(fn): return fn return exe
Example #15
Source File: msvccompiler.py From ironpython2 with Apache License 2.0 | 6 votes |
def get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ prefix = "MSC v." i = string.find(sys.version, prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 if majorVersion >= 6: return majorVersion + minorVersion # else we don't know what version of the compiler this is return None
Example #16
Source File: vssutil.py From ironpython2 with Apache License 2.0 | 6 votes |
def SubstituteInString(inString, evalEnv): substChar = "$" fields = string.split(inString, substChar) newFields = [] for i in range(len(fields)): didSubst = 0 strVal = fields[i] if i%2!=0: try: strVal = eval(strVal,evalEnv[0], evalEnv[1]) newFields.append(strVal) didSubst = 1 except: traceback.print_exc() print "Could not substitute", strVal if not didSubst: newFields.append(strVal) return string.join(map(str, newFields), "")
Example #17
Source File: platform.py From meddle with MIT License | 6 votes |
def _norm_version(version, build=''): """ Normalize the version and build strings and return a single version string using the format major.minor.build (or patchlevel). """ l = string.split(version,'.') if build: l.append(build) try: ints = map(int,l) except ValueError: strings = l else: strings = map(str,ints) version = string.join(strings[:3],'.') return version
Example #18
Source File: pydoc.py From meddle with MIT License | 6 votes |
def help(self, request): if type(request) is type(''): request = request.strip() if request == 'help': self.intro() elif request == 'keywords': self.listkeywords() elif request == 'symbols': self.listsymbols() elif request == 'topics': self.listtopics() elif request == 'modules': self.listmodules() elif request[:8] == 'modules ': self.listmodules(split(request)[1]) elif request in self.symbols: self.showsymbol(request) elif request in self.keywords: self.showtopic(request) elif request in self.topics: self.showtopic(request) elif request: doc(request, 'Help on %s:') elif isinstance(request, Helper): self() else: doc(request, 'Help on %s:') self.output.write('\n')
Example #19
Source File: pydoc.py From meddle with MIT License | 6 votes |
def locate(path, forceload=0): """Locate an object by name or dotted path, importing as necessary.""" parts = [part for part in split(path, '.') if part] module, n = None, 0 while n < len(parts): nextmodule = safeimport(join(parts[:n+1], '.'), forceload) if nextmodule: module, n = nextmodule, n + 1 else: break if module: object = module for part in parts[n:]: try: object = getattr(object, part) except AttributeError: return None return object else: if hasattr(__builtin__, path): return getattr(__builtin__, path) # --------------------------------------- interactive interpreter interface
Example #20
Source File: pydoc.py From meddle with MIT License | 6 votes |
def source_synopsis(file): line = file.readline() while line[:1] == '#' or not strip(line): line = file.readline() if not line: break line = strip(line) if line[:4] == 'r"""': line = line[1:] if line[:3] == '"""': line = line[3:] if line[-1:] == '\\': line = line[:-1] while not strip(line): line = file.readline() if not line: break result = strip(split(line, '"""')[0]) else: result = None return result
Example #21
Source File: bdist_rpm.py From meddle with MIT License | 6 votes |
def _format_changelog(self, changelog): """Format the changelog correctly and convert it to a list of strings """ if not changelog: return changelog new_changelog = [] for line in string.split(string.strip(changelog), '\n'): line = string.strip(line) if line[0] == '*': new_changelog.extend(['', line]) elif line[0] == '-': new_changelog.append(line) else: new_changelog.append(' ' + line) # strip trailing newline inserted by first changelog entry if not new_changelog[0]: del new_changelog[0] return new_changelog # _format_changelog() # class bdist_rpm
Example #22
Source File: msvccompiler.py From meddle with MIT License | 6 votes |
def get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ prefix = "MSC v." i = string.find(sys.version, prefix) if i == -1: return 6 i = i + len(prefix) s, rest = sys.version[i:].split(" ", 1) majorVersion = int(s[:-2]) - 6 minorVersion = int(s[2:3]) / 10.0 # I don't think paths are affected by minor version in version 6 if majorVersion == 6: minorVersion = 0 if majorVersion >= 6: return majorVersion + minorVersion # else we don't know what version of the compiler this is return None
Example #23
Source File: nmb.py From CVE-2017-7494 with GNU General Public License v3.0 | 6 votes |
def encode_name(name, type, scope): if name == '*': name += '\0' * 15 elif len(name) > 15: name = name[:15] + chr(type) else: name = string.ljust(name, 15) + chr(type) encoded_name = chr(len(name) * 2) + re.sub('.', _do_first_level_encoding, name) if scope: encoded_scope = '' for s in string.split(scope, '.'): encoded_scope = encoded_scope + chr(len(s)) + s return encoded_name + encoded_scope + '\0' else: return encoded_name.encode('ascii') + '\0' # Internal method for use in encode_name()
Example #24
Source File: pydoc.py From meddle with MIT License | 5 votes |
def showtopic(self, topic, more_xrefs=''): try: import pydoc_data.topics except ImportError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. ''') return target = self.topics.get(topic, self.keywords.get(topic)) if not target: self.output.write('no documentation found for %s\n' % repr(topic)) return if type(target) is type(''): return self.showtopic(target, more_xrefs) label, xrefs = target try: doc = pydoc_data.topics.topics[label] except KeyError: self.output.write('no documentation found for %s\n' % repr(topic)) return pager(strip(doc) + '\n') if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs if xrefs: import StringIO, formatter buffer = StringIO.StringIO() formatter.DumbWriter(buffer).send_flowing_data( 'Related help topics: ' + join(split(xrefs), ', ') + '\n') self.output.write('\n%s\n' % buffer.getvalue())
Example #25
Source File: make_meta1.py From ironpython2 with Apache License 2.0 | 5 votes |
def __init__(self, ret_type, name, params, mods=None): self.param_list = map(lambda s: s.strip(), string.split(params, ",")) self.param_list = filter(lambda s: s, self.param_list) self.ret_type = ret_type self.name = name self.mods = mods self.is_invokable = True
Example #26
Source File: inspect.py From meddle with MIT License | 5 votes |
def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: return None else: # Find minimum indentation of any non-blank lines after first line. margin = sys.maxint for line in lines[1:]: content = len(string.lstrip(line)) if content: indent = len(line) - content margin = min(margin, indent) # Remove indentation. if lines: lines[0] = lines[0].lstrip() if margin < sys.maxint: for i in range(1, len(lines)): lines[i] = lines[i][margin:] # Remove any trailing or leading blank lines. while lines and not lines[-1]: lines.pop() while lines and not lines[0]: lines.pop(0) return string.join(lines, '\n')
Example #27
Source File: platform.py From meddle with MIT License | 5 votes |
def python_version_tuple(): """ Returns the Python version as tuple (major, minor, patchlevel) of strings. Note that unlike the Python sys.version, the returned value will always include the patchlevel (it defaults to 0). """ return tuple(string.split(_sys_version()[1], '.'))
Example #28
Source File: platform.py From meddle with MIT License | 5 votes |
def _parse_release_file(firstline): # Default to empty 'version' and 'id' strings. Both defaults are used # when 'firstline' is empty. 'id' defaults to empty when an id can not # be deduced. version = '' id = '' # Parse the first line m = _lsb_release_version.match(firstline) if m is not None: # LSB format: "distro release x.x (codename)" return tuple(m.groups()) # Pre-LSB format: "distro x.x (codename)" m = _release_version.match(firstline) if m is not None: return tuple(m.groups()) # Unkown format... take the first two words l = string.split(string.strip(firstline)) if l: version = l[0] if len(l) > 1: id = l[1] return '', version, id
Example #29
Source File: pydoc.py From meddle with MIT License | 5 votes |
def repr1(self, x, level): if hasattr(type(x), '__name__'): methodname = 'repr_' + join(split(type(x).__name__), '_') if hasattr(self, methodname): return getattr(self, methodname)(x, level) return cram(stripid(repr(x)), self.maxother)
Example #30
Source File: pydoc.py From meddle with MIT License | 5 votes |
def indent(self, text, prefix=' '): """Indent text by prepending a given prefix to each line.""" if not text: return '' lines = split(text, '\n') lines = map(lambda line, prefix=prefix: prefix + line, lines) if lines: lines[-1] = rstrip(lines[-1]) return join(lines, '\n')