本文整理汇总了Python中string.replace方法的典型用法代码示例。如果您正苦于以下问题:Python string.replace方法的具体用法?Python string.replace怎么用?Python string.replace使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string
的用法示例。
在下文中一共展示了string.replace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getIndex
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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)
示例2: __getitem__
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
#
示例3: main
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
示例4: copy_file
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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()
示例5: mkdir
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
示例6: rmdir
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
示例7: storeFile
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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)
示例8: check_dir
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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)
示例9: rmdir
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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)
示例10: rename
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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)
示例11: get_chatwheel_sound
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
示例12: __init__
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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]
示例13: getWord
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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`)
示例14: keys
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
示例15: has_key
# 需要导入模块: import string [as 别名]
# 或者: from string import replace [as 别名]
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
#