Python string.index() Examples

The following are 30 code examples for showing how to use string.index(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module string , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testKeys(self):
	"""Verify that index lookup can find each word in the index file."""
	print "Testing: ", self
	file = open(self.indexFile.file.name, _FILE_OPEN_MODE)
	counter = 0
	while 1:
	    line = file.readline()
	    if line == '': break
	    if line[0] != ' ':
		key = string.replace(line[:string.find(line, ' ')], '_', ' ')
		if (counter % 1000) == 0:
		    print "%s..." % (key,),
		    import sys
		    sys.stdout.flush()
		counter = counter + 1
		self[key]
	file.close()
	print "done." 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _index(key, sequence, testfn=None, keyfn=None):
    """Return the index of key within sequence, using testfn for
    comparison and transforming items of sequence by keyfn first.
    
    >>> _index('e', 'hello')
    1
    >>> _index('E', 'hello', testfn=_equalsIgnoreCase)
    1
    >>> _index('x', 'hello')
    """
    index = 0
    for element in sequence:
	value = element
	if keyfn:
	    value = keyfn(value)
	if (not testfn and value == key) or (testfn and testfn(value, key)):
	    return index
	index = index + 1
    return None 
Example 3
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _testKeys(self):
	"""Verify that index lookup can find each word in the index file."""
	print "Testing: ", self
	file = open(self.indexFile.file.name, _FILE_OPEN_MODE)
	counter = 0
	while 1:
	    line = file.readline()
	    if line == '': break
	    if line[0] != ' ':
		key = string.replace(line[:string.find(line, ' ')], '_', ' ')
		if (counter % 1000) == 0:
		    print "%s..." % (key,),
		    import sys
		    sys.stdout.flush()
		counter = counter + 1
		self[key]
	file.close()
	print "done." 
Example 4
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _index(key, sequence, testfn=None, keyfn=None):
    """Return the index of key within sequence, using testfn for
    comparison and transforming items of sequence by keyfn first.
    
    >>> _index('e', 'hello')
    1
    >>> _index('E', 'hello', testfn=_equalsIgnoreCase)
    1
    >>> _index('x', 'hello')
    """
    index = 0
    for element in sequence:
	value = element
	if keyfn:
	    value = keyfn(value)
	if (not testfn and value == key) or (testfn and testfn(value, key)):
	    return index
	index = index + 1
    return None 
Example 5
Project: nightmare   Author: joxeankoret   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
def do_call(self, string):
        """
        Allows a C-like syntax for calling functions inside
        the target process (from his context).
        Example: call printf("yermom %d", 10)
        """
        self.trace.requireAttached()
        ind = string.index("(")
        if ind == -1:
            raise Exception('ERROR - call wants c-style syntax: ie call printf("yermom")')
        funcaddr = self.trace.parseExpression(string[:ind])

        try:
            args = eval(string[ind:])
        except:
            raise Exception('ERROR - call wants c-style syntax: ie call printf("yermom")')

        self.vprint("calling %s -> 0x%.8x" % (string[:ind], funcaddr))
        self.trace.call(funcaddr, args) 
Example 6
Project: mxnet-lambda   Author: awslabs   File: PcfFontFile.py    License: Apache License 2.0 6 votes vote down vote up
def _load_encoding(self):

        # map character code to bitmap index
        encoding = [None] * 256

        fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)

        firstCol, lastCol = i16(fp.read(2)), i16(fp.read(2))
        firstRow, lastRow = i16(fp.read(2)), i16(fp.read(2))

        default = i16(fp.read(2))

        nencoding = (lastCol - firstCol + 1) * (lastRow - firstRow + 1)

        for i in range(nencoding):
            encodingOffset = i16(fp.read(2))
            if encodingOffset != 0xFFFF:
                try:
                    encoding[i+firstCol] = encodingOffset
                except IndexError:
                    break # only load ISO-8859-1 glyphs

        return encoding 
Example 7
Project: Leetcode   Author: UmassJin   File: google面经集合.py    License: MIT License 6 votes vote down vote up
def count_frequency(array):
    if not array: return None
    n = len(array)
    i = 0

    while i < n:
        if array[i] < 0:
            i += 1
            continue
        index = array[i] - 1
        if array[index] > 0:
            array[i] = array[index]
            array[index] = -1
        else:
            array[index] -= 1
            array[i] = 0
            i += 1
    return array 
Example 8
Project: Leetcode   Author: UmassJin   File: google面经集合.py    License: MIT License 6 votes vote down vote up
def max_length_loop(array):
    def dfs(index, len):
        if visited[index]:
            result[0] = max(result[0], len-length[index])
            return 
        visited[index] = True
        length[index] = len
        dfs(array[index], len + 1)

    if not array:
        return 0
    n = len(array)
    visited = [False for _ in xrange(n)]
    length = [0 for _ in xrange(n)]
    result = [0]
    for i in xrange(n): # check each index in the array 
        dfs(i, 0)
    return result[0] 
Example 9
Project: Leetcode   Author: UmassJin   File: google面经集合.py    License: MIT License 6 votes vote down vote up
def count_number(array):
    if not array:
        return None
    count = 0; step = 1; number = array[0]
    index = 0
    result = []
    n = len(array)
    while index < n:
        count += step
        step *= 2
        if index + step >= n or array[index+step] != number:
            step = 1
            if index + step < n and array[index+step] != number:
                result.append((number, count))
                count = 0
                number = array[index+step]
        index += step
    result.append((number, count))
    return result 
Example 10
Project: CNCGToolKit   Author: cineuse   File: PcfFontFile.py    License: MIT License 6 votes vote down vote up
def _load_encoding(self):

        # map character code to bitmap index
        encoding = [None] * 256

        fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)

        firstCol, lastCol = i16(fp.read(2)), i16(fp.read(2))
        firstRow, lastRow = i16(fp.read(2)), i16(fp.read(2))

        default = i16(fp.read(2))

        nencoding = (lastCol - firstCol + 1) * (lastRow - firstRow + 1)

        for i in range(nencoding):
            encodingOffset = i16(fp.read(2))
            if encodingOffset != 0xFFFF:
                try:
                    encoding[i+firstCol] = encodingOffset
                except IndexError:
                    break # only load ISO-8859-1 glyphs

        return encoding 
Example 11
Project: keras-lambda   Author: sunilmallya   File: PcfFontFile.py    License: MIT License 6 votes vote down vote up
def _load_encoding(self):

        # map character code to bitmap index
        encoding = [None] * 256

        fp, format, i16, i32 = self._getformat(PCF_BDF_ENCODINGS)

        firstCol, lastCol = i16(fp.read(2)), i16(fp.read(2))
        firstRow, lastRow = i16(fp.read(2)), i16(fp.read(2))

        default = i16(fp.read(2))

        nencoding = (lastCol - firstCol + 1) * (lastRow - firstRow + 1)

        for i in range(nencoding):
            encodingOffset = i16(fp.read(2))
            if encodingOffset != 0xFFFF:
                try:
                    encoding[i+firstCol] = encodingOffset
                except IndexError:
                    break # only load ISO-8859-1 glyphs

        return encoding 
Example 12
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	return self.getSenses()[index] 
Example 13
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos, offset, line):
        "Initialize the synset from a line off a WN synset file."
	self.pos = pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB."
	self.offset = offset
        """integer offset into the part-of-speech file.  Together
        with pos, this can be used as a unique id."""
	tokens = string.split(line[:string.index(line, '|')])
	self.ssType = tokens[2]
	self.gloss = string.strip(line[string.index(line, '|') + 1:])
        self.lexname = Lexname.lexnames[int(tokens[1])]
	(self._senseTuples, remainder) = _partition(tokens[4:], 2, string.atoi(tokens[3], 16))
	(self._pointerTuples, remainder) = _partition(remainder[1:], 4, int(remainder[0]))
	if pos == VERB:
	    (vfTuples, remainder) = _partition(remainder[1:], 3, int(remainder[0]))
	    def extractVerbFrames(index, vfTuples):
		return tuple(map(lambda t:string.atoi(t[1]), filter(lambda t,i=index:string.atoi(t[2],16) in (0, i), vfTuples)))
	    senseVerbFrames = []
	    for index in range(1, len(self._senseTuples) + 1):
		senseVerbFrames.append(extractVerbFrames(index, vfTuples))
	    self._senseVerbFrames = senseVerbFrames
	    self.verbFrames = tuple(extractVerbFrames(None, vfTuples))
            """A sequence of integers that index into
            VERB_FRAME_STRINGS. These list the verb frames that any
            Sense in this synset participates in.  (See also
            Sense.verbFrames.) Defined only for verbs.""" 
Example 14
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(sense, synset, senseTuple, verbFrames=None):
        "Initialize a sense from a synset's senseTuple."
	# synset is stored by key (pos, synset) rather than object
	# reference, to avoid creating a circular reference between
	# Senses and Synsets that will prevent the vm from
	# garbage-collecting them.
	sense.pos = synset.pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB"
	sense.synsetOffset = synset.offset
        "synset key.  This is used to retrieve the sense."
	sense.verbFrames = verbFrames
        """A sequence of integers that index into
        VERB_FRAME_STRINGS. These list the verb frames that this
        Sense partipates in.  Defined only for verbs."""
	(form, idString) = senseTuple
	sense.position = None
	if '(' in form:
	    index = string.index(form, '(')
	    key = form[index + 1:-1]
	    form = form[:index]
	    if key == 'a':
		sense.position = ATTRIBUTIVE
	    elif key == 'p':
		sense.position = PREDICATIVE
	    elif key == 'ip':
		sense.position = IMMEDIATE_POSTNOMINAL
	    else:
		raise "unknown attribute " + key
	sense.form = string.replace(form, '_', ' ')
        "orthographic representation of the Word this is a Sense of." 
Example 15
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __nonzero__(self):
	"""Return false.  (This is to avoid scanning the whole index file
	to compute len when a Dictionary is used in test position.)
	
	>>> N and 'true'
	'true'
	"""
	return 1 
Example 16
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __len__(self):
	"""Return the number of index entries.
	
	>>> len(ADJ)
	21435
	"""
	if not hasattr(self, 'length'):
	    self.length = len(self.indexFile)
	return self.length 
Example 17
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def keys(self):
	"""Return a sorted list of strings that index words in this
	dictionary."""
	return self.indexFile.keys() 
Example 18
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 19
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _indexFilePathname(filenameroot):
    if os.name in ('dos', 'nt'):
	path = os.path.join(WNSEARCHDIR, filenameroot + ".idx")
        if os.path.exists(path):
            return path
    return os.path.join(WNSEARCHDIR, "index." + filenameroot) 
Example 20
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	return self.getSenses()[index] 
Example 21
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pos, offset, line):
        "Initialize the synset from a line off a WN synset file."
	self.pos = pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB."
	self.offset = offset
        """integer offset into the part-of-speech file.  Together
        with pos, this can be used as a unique id."""
	tokens = string.split(line[:string.index(line, '|')])
	self.ssType = tokens[2]
	self.gloss = string.strip(line[string.index(line, '|') + 1:])
        self.lexname = Lexname.lexnames[int(tokens[1])]
	(self._senseTuples, remainder) = _partition(tokens[4:], 2, string.atoi(tokens[3], 16))
	(self._pointerTuples, remainder) = _partition(remainder[1:], 4, int(remainder[0]))
	if pos == VERB:
	    (vfTuples, remainder) = _partition(remainder[1:], 3, int(remainder[0]))
	    def extractVerbFrames(index, vfTuples):
		return tuple(map(lambda t:string.atoi(t[1]), filter(lambda t,i=index:string.atoi(t[2],16) in (0, i), vfTuples)))
	    senseVerbFrames = []
	    for index in range(1, len(self._senseTuples) + 1):
		senseVerbFrames.append(extractVerbFrames(index, vfTuples))
	    self._senseVerbFrames = senseVerbFrames
	    self.verbFrames = tuple(extractVerbFrames(None, vfTuples))
            """A sequence of integers that index into
            VERB_FRAME_STRINGS. These list the verb frames that any
            Sense in this synset participates in.  (See also
            Sense.verbFrames.) Defined only for verbs.""" 
Example 22
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(sense, synset, senseTuple, verbFrames=None):
        "Initialize a sense from a synset's senseTuple."
	# synset is stored by key (pos, synset) rather than object
	# reference, to avoid creating a circular reference between
	# Senses and Synsets that will prevent the vm from
	# garbage-collecting them.
	sense.pos = synset.pos
        "part of speech -- one of NOUN, VERB, ADJECTIVE, ADVERB"
	sense.synsetOffset = synset.offset
        "synset key.  This is used to retrieve the sense."
	sense.verbFrames = verbFrames
        """A sequence of integers that index into
        VERB_FRAME_STRINGS. These list the verb frames that this
        Sense partipates in.  Defined only for verbs."""
	(form, idString) = senseTuple
	sense.position = None
	if '(' in form:
	    index = string.index(form, '(')
	    key = form[index + 1:-1]
	    form = form[:index]
	    if key == 'a':
		sense.position = ATTRIBUTIVE
	    elif key == 'p':
		sense.position = PREDICATIVE
	    elif key == 'ip':
		sense.position = IMMEDIATE_POSTNOMINAL
	    else:
		raise "unknown attribute " + key
	sense.form = string.replace(form, '_', ' ')
        "orthographic representation of the Word this is a Sense of." 
Example 23
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __nonzero__(self):
	"""Return false.  (This is to avoid scanning the whole index file
	to compute len when a Dictionary is used in test position.)
	
	>>> N and 'true'
	'true'
	"""
	return 1 
Example 24
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __len__(self):
	"""Return the number of index entries.
	
	>>> len(ADJ)
	21435
	"""
	if not hasattr(self, 'length'):
	    self.length = len(self.indexFile)
	return self.length 
Example 25
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def keys(self):
	"""Return a sorted list of strings that index words in this
	dictionary."""
	return self.indexFile.keys() 
Example 26
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 27
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _indexFilePathname(filenameroot):
    if os.name in ('dos', 'nt'):
	path = os.path.join(WNSEARCHDIR, filenameroot + ".idx")
        if os.path.exists(path):
            return path
    return os.path.join(WNSEARCHDIR, "index." + filenameroot) 
Example 28
Project: CVE-2017-7494   Author: joxeankoret   File: smb.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, ctime, atime, mtime, filesize, allocsize, attribs, shortname, longname):
        self.__ctime = ctime
        self.__atime = atime
        self.__mtime = mtime
        self.__filesize = filesize
        self.__allocsize = allocsize
        self.__attribs = attribs
        try:
            self.__shortname = shortname[:string.index(shortname, '\0')]
        except ValueError:
            self.__shortname = shortname
        try:
            self.__longname = longname[:string.index(longname, '\0')]
        except ValueError:
            self.__longname = longname 
Example 29
Project: Computable   Author: ktraunmueller   File: ic.py    License: MIT License 5 votes vote down vote up
def _decode(data, key):
    if '\245' in key:
        key2 = key[:string.index(key, '\245')+1]
    else:
        key2 = key
    if key2 in _decoder_table:
        decoder = _decoder_table[key2][0]
    else:
        decoder = _decode_default
    return decoder(data, key) 
Example 30
Project: Computable   Author: ktraunmueller   File: ic.py    License: MIT License 5 votes vote down vote up
def _code(data, key):
    if type(data) == _ICOpaqueDataType:
        return data.data
    if '\245' in key:
        key2 = key[:string.index(key, '\245')+1]
    else:
        key2 = key
    if key2 in _decoder_table:
        coder = _decoder_table[key2][1]
    else:
        coder = _code_default
    return coder(data, key)