Python string.replace() Examples

The following are 30 code examples for showing how to use string.replace(). 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: wntools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 3
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getIndex(form, pos='noun'):
    """Search for _form_ in the index file corresponding to
    _pos_. getIndex applies to _form_ an algorithm that replaces
    underscores with hyphens, hyphens with underscores, removes
    hyphens and underscores, and removes periods in an attempt to find
    a form of the string that is an exact match for an entry in the
    index file corresponding to _pos_.  getWord() is called on each
    transformed string until a match is found or all the different
    strings have been tried. It returns a Word or None."""
    def trySubstitutions(trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor(pos)):
        if lookup and dictionary.has_key(form):
            return dictionary[form]
        elif substitutions:
            (old, new) = substitutions[0]
            substitute = string.replace(form, old, new) and substitute != form
            if substitute and dictionary.has_key(substitute):
                return dictionary[substitute]
            return              trySubstitutions(trySubstitutions, form, substitutions[1:], lookup=0) or \
                (substitute and trySubstitutions(trySubstitutions, substitute, substitutions[1:]))
    return trySubstitutions(returnMatch, form, GET_INDEX_SUBSTITUTIONS) 
Example 4
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 5
Project: Python-John-Zelle-book   Author: sai29   File: 9.py    License: MIT License 6 votes vote down vote up
def main():
    print "This program converts a textual message into a sequence"
    print "of numbers representing the ASCII encoding of the message."
    print
    
    # Get the message to encode
    message = raw_input("Please enter the message to encode: ")
    n = int(raw_input("Enter the key value"))
    print
    print "Here are the ASCII codes:"
    z = string.replace(message,"z","a")
    z1 = string.replace(z,"Z","A")
    
    # Loop through the message and print out the ASCII values
    for ch in z1:
        a = chr(ord(ch) + n),   # use comma to print all on one line.
        print " ".join(a),
    print 
Example 6
Project: CVE-2017-7494   Author: joxeankoret   File: serviceinstall.py    License: GNU General Public License v3.0 6 votes vote down vote up
def copy_file(self, src, tree, dst):
        LOG.info("Uploading file %s" % dst)
        if isinstance(src, str):
            # We have a filename
            fh = open(src, 'rb')
        else:
            # We have a class instance, it must have a read method
            fh = src
        f = dst
        pathname = string.replace(f,'/','\\')
        try:
            self.connection.putFile(tree, pathname, fh.read)
        except:
            LOG.critical("Error uploading file %s, aborting....." % dst)
            raise
        fh.close() 
Example 7
Project: CVE-2017-7494   Author: joxeankoret   File: smb3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def mkdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)          
        finally:
            if fileId is not None:
                self.close(treeId, fileId)            
            self.disconnectTree(treeId) 

        return True 
Example 8
Project: CVE-2017-7494   Author: joxeankoret   File: smb3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def rmdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                 shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                 creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
                                 creationDisposition=FILE_OPEN, fileAttributes=0)
            from impacket import smb
            delete_req = smb.SMBSetFileDispositionInfo()
            delete_req['DeletePending'] = True
            self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
Example 9
Project: CVE-2017-7494   Author: joxeankoret   File: smb3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
        # ToDo: Handle situations where share is password protected
        path = string.replace(path,'/', '\\')
        path = ntpath.normpath(path)
        if len(path) > 0 and path[0] == '\\':
            path = path[1:]

        treeId = self.connectTree(shareName)
        fileId = None
        try:
            fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
            finished = False
            writeOffset = offset
            while not finished:
                data = callback(self._Connection['MaxWriteSize'])
                if len(data) == 0:
                    break
                written = self.write(treeId, fileId, data, writeOffset, len(data))
                writeOffset += written
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 
Example 10
Project: CVE-2017-7494   Author: joxeankoret   File: smb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def check_dir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Mid'] = 0

            cmd = SMBCommand(SMB.SMB_COM_CHECK_DIRECTORY)
            cmd['Parameters'] = ''
            cmd['Data'] = SMBCheckDirectory_Data(flags = self.__flags2)
            cmd['Data']['DirectoryName'] = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path
            smb.addCommand(cmd)

            self.sendSMB(smb)

            while 1:
                s = self.recvSMB()
                if s.isValidAnswer(SMB.SMB_COM_CHECK_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid) 
Example 11
Project: CVE-2017-7494   Author: joxeankoret   File: smb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def rmdir(self, service, path, password = None):
        path = string.replace(path,'/', '\\')
        # Check that the directory exists
        self.check_dir(service, path, password)

        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            path = path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else path

            smb = NewSMBPacket()
            smb['Tid'] = tid
            createDir = SMBCommand(SMB.SMB_COM_DELETE_DIRECTORY)
            createDir['Data'] = SMBDeleteDirectory_Data(flags=self.__flags2)
            createDir['Data']['DirectoryName'] = path
            smb.addCommand(createDir)

            self.sendSMB(smb)

            while 1:
                s = self.recvSMB()
                if s.isValidAnswer(SMB.SMB_COM_DELETE_DIRECTORY):
                    return
        finally:
            self.disconnect_tree(tid) 
Example 12
Project: CVE-2017-7494   Author: joxeankoret   File: smb.py    License: GNU General Public License v3.0 6 votes vote down vote up
def rename(self, service, old_path, new_path, password = None):
        old_path = string.replace(old_path,'/', '\\')
        new_path = string.replace(new_path,'/', '\\')
        tid = self.tree_connect_andx('\\\\' + self.__remote_name + '\\' + service, password)
        try:
            smb = NewSMBPacket()
            smb['Tid'] = tid
            smb['Mid'] = 0

            renameCmd = SMBCommand(SMB.SMB_COM_RENAME)
            renameCmd['Parameters'] = SMBRename_Parameters()
            renameCmd['Parameters']['SearchAttributes'] = ATTR_SYSTEM | ATTR_HIDDEN | ATTR_DIRECTORY
            renameCmd['Data'] = SMBRename_Data(flags = self.__flags2)
            renameCmd['Data']['OldFileName'] = old_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else old_path
            renameCmd['Data']['NewFileName'] = new_path.encode('utf-16le') if self.__flags2 & SMB.FLAGS2_UNICODE else new_path
            smb.addCommand(renameCmd)

            self.sendSMB(smb)

            smb = self.recvSMB()
            if smb.isValidAnswer(SMB.SMB_COM_RENAME):
               return 1
            return 0
        finally:
            self.disconnect_tree(tid) 
Example 13
Project: MangoByte   Author: mdiller   File: dotabase.py    License: MIT License 6 votes vote down vote up
def get_chatwheel_sound(self, text, loose_fit=False):
		def simplify(t):
			t = re.sub(r"[?!',!?.-]", "", t.lower())
			return re.sub(r"[_,]", " ", t)
		text = simplify(text)
		if text == "":
			return None
		for message in session.query(ChatWheelMessage):
			if message.sound:
				strings = list(map(simplify, [ message.name, message.message, message.label ]))
				if text in strings:
					return message
				if loose_fit:
					for string in strings:
						if text.replace(" ", "") == string.replace(" ", ""):
							return message
					for string in strings:
						if text in string:
							return message
		return None 
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__(self, line):
        """Initialize the word from a line of a WN POS file."""
	tokens = string.split(line)
	ints = map(int, tokens[int(tokens[3]) + 4:])
	self.form = string.replace(tokens[0], '_', ' ')
        "Orthographic representation of the word."
	self.pos = _normalizePOS(tokens[1])
        "Part of speech.  One of NOUN, VERB, ADJECTIVE, ADVERB."
	self.taggedSenseCount = ints[1]
        "Number of senses that are tagged."
	self._synsetOffsets = ints[2:ints[0]+2] 
Example 15
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 16
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getWord(self, form, line=None):
	key = string.replace(string.lower(form), ' ', '_')
	pos = self.pos
	def loader(key=key, line=line, indexFile=self.indexFile):
	    line = line or indexFile.get(key)
	    return line and Word(line)
	word = _entityCache.get((pos, key), loader)
	if word:
	    return word
	else:
	    raise KeyError, "%s is not in the %s database" % (`form`, `pos`) 
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):
	if hasattr(self, 'indexCache'):
	    keys = self.indexCache.keys()
	    keys.sort()
	    return keys
	else:
	    keys = []
	    self.rewind()
	    while 1:
		line = self.file.readline()
		if not line: break
                key = line.split(' ', 1)[0]
		keys.append(key.replace('_', ' '))
	    return 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 has_key(self, key):
	key = key.replace(' ', '_') # test case: V['haze over']
	if hasattr(self, 'indexCache'):
	    return self.indexCache.has_key(key)
	return self.get(key) != None
    
    #
    # Index file
    # 
Example 19
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
        return self._children[index]

    ##
    # Replaces the given subelement.
    #
    # @param index What subelement to replace.
    # @param element The new element value.
    # @exception IndexError If the given element does not exist.
    # @exception AssertionError If element is not a valid object. 
Example 20
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getslice__(self, start, stop):
        return self._children[start:stop]

    ##
    # Replaces a number of subelements with elements from a sequence.
    #
    # @param start The first subelement to replace.
    # @param stop The first subelement that shouldn't be replaced.
    # @param elements A sequence object with zero or more elements.
    # @exception AssertionError If a sequence member is not a valid object. 
Example 21
Project: razzy-spinner   Author: rafasashi   File: ElementTree.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _escape_cdata(text, encoding=None, replace=string.replace):
    # escape character data
    try:
        if encoding:
            try:
                text = _encode(text, encoding)
            except UnicodeError:
                return _encode_entity(text)
        text = replace(text, "&", "&")
        text = replace(text, "<", "&lt;")
        text = replace(text, ">", "&gt;")
        return text
    except (TypeError, AttributeError):
        _raise_serialization_error(text) 
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__(self, line):
        """Initialize the word from a line of a WN POS file."""
	tokens = string.split(line)
	ints = map(int, tokens[int(tokens[3]) + 4:])
	self.form = string.replace(tokens[0], '_', ' ')
        "Orthographic representation of the word."
	self.pos = _normalizePOS(tokens[1])
        "Part of speech.  One of NOUN, VERB, ADJECTIVE, ADVERB."
	self.taggedSenseCount = ints[1]
        "Number of senses that are tagged."
	self._synsetOffsets = ints[2:ints[0]+2] 
Example 23
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 24
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getWord(self, form, line=None):
	key = string.replace(string.lower(form), ' ', '_')
	pos = self.pos
	def loader(key=key, line=line, indexFile=self.indexFile):
	    line = line or indexFile.get(key)
	    return line and Word(line)
	word = _entityCache.get((pos, key), loader)
	if word:
	    return word
	else:
	    raise KeyError, "%s is not in the %s database" % (`form`, `pos`) 
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):
	if hasattr(self, 'indexCache'):
	    keys = self.indexCache.keys()
	    keys.sort()
	    return keys
	else:
	    keys = []
	    self.rewind()
	    while 1:
		line = self.file.readline()
		if not line: break
                key = line.split(' ', 1)[0]
		keys.append(key.replace('_', ' '))
	    return 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 has_key(self, key):
	key = key.replace(' ', '_') # test case: V['haze over']
	if hasattr(self, 'indexCache'):
	    return self.indexCache.has_key(key)
	return self.get(key) != None
    
    #
    # Index file
    # 
Example 27
Project: verge3d-blender-addon   Author: Soft8Soft   File: newbytes.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fromhex(cls, string):
        # Only on Py2:
        return cls(string.replace(' ', '').decode('hex')) 
Example 28
Project: verge3d-blender-addon   Author: Soft8Soft   File: newbytes.py    License: GNU General Public License v3.0 5 votes vote down vote up
def replace(self, old, new, *args):
        return newbytes(super(newbytes, self).replace(old, new, *args)) 
Example 29
Project: Python-John-Zelle-book   Author: sai29   File: 11.py    License: MIT License 5 votes vote down vote up
def main():
	text = raw_input("Enter the text: ")
	text1 = string.split(text)
	a = len(text1)
	text2 = string.replace(text," ","")
	b = len(text2)
	c = (float(b)/a)
	print "The average number of words is", c 
Example 30
Project: misp42splunk   Author: remg427   File: newbytes.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def fromhex(cls, string):
        # Only on Py2:
        return cls(string.replace(' ', '').decode('hex'))