我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用string.rfind()。
def printexpr(expr_string): """ printexpr(expr) - print the value of the expression, along with linenumber and filename. """ stack = extract_stack ( )[-2:][0] actualCall = stack[3] left = string.find ( actualCall, '(' ) right = string.rfind ( actualCall, ')' ) caller_globals,caller_locals = _caller_symbols() expr = eval(expr_string,caller_globals,caller_locals) varType = type( expr ) stderr.write("%s:%d> %s == %s (%s)\n" % ( stack[0], stack[1], string.strip( actualCall[left+1:right] )[1:-1], repr(expr), str(varType)[7:-2]))
def lineReceived(self, line): parts = string.split(line) if not parts: parts = [''] if len(parts) == 1: slash_w = 0 else: slash_w = 1 user = parts[-1] if '@' in user: host_place = string.rfind(user, '@') user = user[:host_place] host = user[host_place+1:] return self.forwardQuery(slash_w, user, host) if user: return self.getUser(slash_w, user) else: return self.getDomain(slash_w)
def write(self, out_filename): """Create the FFFF file Create the FFFF file, write the FFFF ROMimage buffer to it and return a success flag. Appends the default FFFF file extension if omitted """ # Reject the write if we didn't pass the sniff test if self.ffff0.header_validity != FFFF_HDR_VALID: raise ValueError("Invalid FFFF header 0") if self.ffff1.header_validity != FFFF_HDR_VALID: raise ValueError("Invalid FFFF header 1") # Ensure the output file ends in the default file extension if # the user hasn't specified their own extension. if rfind(out_filename, ".") == -1: out_filename += FFFF_FILE_EXTENSION # Output the entire FFFF blob with open(out_filename, 'wb') as wf: wf.write(self.ffff_buf) print("Wrote", out_filename) return True
def get_searches(self): elements = re.split('<tr>', self.page) for index in range(1, len(elements), 1): element = elements[index] titleandid = gutils.trim(element, '<td class="title">', '</td>') title = gutils.clean(titleandid) id = gutils.trim(titleandid, 'href="', '"') idstart = string.rfind(id, '/') id = id[idstart + 1:] year = gutils.trim(element, '<td class="year">', '</td>') self.ids.append(id) self.titles.append(title + ' (' + gutils.clean(year)+ ')') # # Plugin Test #
def _fixupParents(self, alogger): """ Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy. """ name = alogger.name i = string.rfind(name, ".") rv = None while (i > 0) and not rv: substr = name[:i] if not self.loggerDict.has_key(substr): self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger): rv = obj else: assert isinstance(obj, PlaceHolder) obj.append(alogger) i = string.rfind(name, ".", 0, i - 1) if not rv: rv = self.root alogger.parent = rv
def mput(outarray,fname,writeheader=0,btype=N.int16): """ Save a file for use in matlab. """ outarray = N.transpose(outarray) outdata = N.ravel(outarray).astype(btype) outdata = outdata.tostring() outfile = open(fname,'wb') outfile.write(outdata) outfile.close() if writeheader == 1: try: suffixindex = string.rfind(fname,'.') hdrname = fname[0:suffixindex] except ValueError: hdrname = fname if len(outarray.shape) == 2: hdr = [outarray.shape[1],outarray.shape[0], 1, 0] else: hdr = [outarray.shape[2],outarray.shape[1],outarray.shape[0], 0,'\n'] print hdrname+'.hdr' outfile = open(hdrname+'.hdr','w') outfile.write(pstat.list2string(hdr)) outfile.close() return None
def getCurrentWord(self, entry): i = entry.get_point() text = entry.get_chars(0,-1) word = re.split(r'\s', text)[-1] start = string.rfind(text, word) end = start+len(word) return (word, (start, end))
def isCursorOnLastLine(entry): if entry.get_point() >= string.rfind(string.rstrip(entry.get_chars(0,-1)), '\n'): return 1
def get_leafname(self, path): """Get the leafname of the specified file.""" pos = string.rfind(path, os.sep) if pos != -1: return path[pos+1:] else: return path
def convert(label): if not label.startswith("//"): sys.stderr.write("expected label to start with //, got %s\n" % label) return 1 base = _remove_sdk_dir(label[2:]) separator_index = string.rfind(base, ":") if separator_index < 0: sys.stderr.write("could not find target name in label %s\n" % label) return 1 path = base[:separator_index].split("/") name = base[separator_index+1:] if path[-1] == name: return ".".join(path) else: return "%s._%s" % (".".join(path), name)
def get_target(label): if not label.startswith("//"): raise Exception("Expected label to start with //, got %s" % label) base = label[2:] separator_index = string.rfind(base, ":") if separator_index >= 0: name = base[separator_index+1:] path = base[:separator_index] else: name = base[base.rfind("/")+1:] path = base return path, name # Updates paths in a TOML block.
def split(p): """ Split a path in head (everything up to the last '.') and tail (the rest). FS name must still be dealt with separately since special field may contain '.'. """ (fs, drive, path)= _split(p) q= string.rfind(path, '.') if q!=-1: return (fs+drive+path[:q], path[q+1:]) return ('', p)
def splitext(p): """ Split a path in root and extension. This assumes the 'using slash for dot and dot for slash with foreign files' convention common in RISC OS is in force. """ (tail, head)= split(p) if '/' in head: q= len(head)-string.rfind(head, '/') return (p[:-q], p[-q:]) return (p, '')
def get_leafname(path): """Get the leafname of the specified file.""" pos = string.rfind(path, os.sep) if pos != -1: return path[pos+1:] else: return path
def write(self, out_filename): """Create the TFTF file and return a success flag Create the TFTF file (appending the default extension if omitted) and write the TFTF buffer to it. """ success = True # Prepare the output buffer self.pack() # Record the length of the entire TFTF blob (this will be longer # than the header's load_length) self.tftf_length = len(self.tftf_buf) # Ensure the output file ends in the default TFTF file extension if # the user hasn't specified their own extension. if rfind(out_filename, ".") == -1: out_filename += TFTF_FILE_EXTENSION try: with open(out_filename, 'wb') as wf: # Write the TFTF header wf.write(self.tftf_buf) # verify the file is the correct length try: statinfo = os.stat(out_filename) if statinfo.st_size != self.tftf_length: error(out_filename, "has wrong length") except: error("Can't get info on", out_filename) except: error("Unable to write", out_filename) success = False else: if success: print("Wrote", out_filename) else: error("Failed to write", out_filename) return success
def __get_background_url(self, url): # background-image: url('http://img.178.com/dota2/201511/241827471049/241827723987.jpg'); start_index = string.find(url, "'") end_index = string.rfind(url, "'") return url[start_index + 1:end_index]
def rtrim(text, key1, key2): p1 = string.rfind(text, key2) if p1 == -1: return '' p2 = string.rfind(text[:p1], key1) if p2 == -1: return "" else: p2 = p2 + len(key1) return text[p2:p1]
def get_trailer(self): # Find the film's trailer page or location self.trailer = '' pos_end = string.find(self.page, '>guarda il trailer<') if pos_end > -1: pos_beg = string.rfind(self.page[:pos_end], '<a href') if pos_beg > -1: self.trailer = gutils.trim(self.page[pos_beg:pos_end], '"', '"')
def get_o_site(self): self.o_site = "" try: index = string.rfind(self.page, u'title="oficiální web"') if index > 0: tmp = gutils.before(self.page, u'title="oficiální web"') index = string.rfind(tmp, 'href="') if index > 0: self.o_site = gutils.trim(tmp[index:], '"', '"') except: pass
def get_nextpage_url(self): match = re.search('(siguientes >|siguientes >)', self.page) if match: start = string.rfind(self.page, '<a href="', 0, match.start()) if start >= 0: return 'http://www.filmaffinity.com/es/' + gutils.before(self.page[start + 9:match.start()], '"') return None
def get_trailer(self): self.trailer = '' tmp = string.find(self.page, u'(trailers)') if tmp >= 0: index = string.rfind(self.page[:tmp], u'<a href="') if index >= 0: self.trailer = gutils.before(self.page[index + 9:], '"')
def rename(source, dest): """ Renames files specified by UNIX inpattern to those specified by UNIX outpattern. Can only handle a single '*' in the two patterns!!! Usage: rename (source, dest) e.g., rename('*.txt', '*.c') """ infiles = glob.glob(source) outfiles = [] incutindex = string.index(source,'*') outcutindex = string.index(source,'*') findpattern1 = source[0:incutindex] findpattern2 = source[incutindex+1:] replpattern1 = dest[0:incutindex] replpattern2 = dest[incutindex+1:] for fname in infiles: if incutindex > 0: newname = re.sub(findpattern1,replpattern1,fname,1) if outcutindex < len(dest)-1: if incutindex > 0: lastone = string.rfind(newname,replpattern2) newname = newname[0:lastone] + re.sub(findpattern2,replpattern2,fname[lastone:],1) else: lastone = string.rfind(fname,findpattern2) if lastone <> -1: newname = fname[0:lastone] newname = newname + re.sub(findpattern2,replpattern2,fname[lastone:],1) os.rename(fname,newname) return
def bput(outarray,fname,writeheader=0,packtype=N.int16,writetype='wb'): """ Writes the passed array to a binary output file, and then closes the file. Default is overwrite the destination file. Usage: bput (outarray,filename,writeheader=0,packtype=N.int16,writetype='wb') """ suffix = fname[-6:] if suffix == 'bshort': packtype = N.int16 elif suffix == 'bfloat': packtype = N.Float32 else: print 'Not a bshort or bfloat file. Using packtype=',packtype outdata = N.ravel(outarray).astype(packtype) littleEndian = ( struct.pack('i',1)==struct.pack('<i',1) ) if littleEndian and os.uname()[0]<>'Linux': outdata = outdata.byteswapped() outdata = outdata.tostring() outfile = open(fname,writetype) outfile.write(outdata) outfile.close() if writeheader == 1: try: suffixindex = string.rfind(fname,'.') hdrname = fname[0:suffixindex] except ValueError: hdrname = fname if len(outarray.shape) == 2: hdr = [outarray.shape[0],outarray.shape[1], 1, 0] else: hdr = [outarray.shape[1],outarray.shape[2],outarray.shape[0], 0,'\n'] print hdrname+'.hdr' outfile = open(hdrname+'.hdr','w') outfile.write(pstat.list2string(hdr)) outfile.close() return None
def __call__(self, twitter, options): statusTxt = (" ".join(options['extra_args']) if options['extra_args'] else str(input("message: "))) replies = [] ptr = re.compile("@[\w_]+") while statusTxt: s = ptr.match(statusTxt) if s and s.start() == 0: replies.append(statusTxt[s.start():s.end()]) statusTxt = statusTxt[s.end() + 1:] else: break replies = " ".join(replies) if len(replies) >= 140: # just go back statusTxt = replies replies = "" splitted = [] while statusTxt: limit = 140 - len(replies) if len(statusTxt) > limit: end = string.rfind(statusTxt, ' ', 0, limit) else: end = limit splitted.append(" ".join((replies, statusTxt[:end]))) statusTxt = statusTxt[end:] if options['invert_split']: splitted.reverse() for status in splitted: twitter.statuses.update(status=status)
def get_extension(path): dirsep = string.rfind(path, '/') dotsep = string.rfind(path, '.') if dotsep > dirsep: return path[dotsep + 1:] else: return ''
def compFiles(res, expected, base1, base2): l1 = len(base1) exp = expected.readlines() expected.close() # the "relativisation" is done here for i in range(len(res)): j = string.find(res[i],base1) if (j == 0) or ((j == 2) and (res[i][0:2] == './')): col = string.find(res[i],':') if col > 0: start = string.rfind(res[i][:col], '/') if start > 0: res[i] = res[i][start+1:] for i in range(len(exp)): j = string.find(exp[i],base2) if (j == 0) or ((j == 2) and (exp[i][0:2] == './')): col = string.find(exp[i],':') if col > 0: start = string.rfind(exp[i][:col], '/') if start > 0: exp[i] = exp[i][start+1:] ret = 0 # ideally we would like to use difflib functions here to do a # nice comparison of the two sets. Unfortunately, during testing # (using python 2.3.3 and 2.3.4) the following code went into # a dead loop under windows. I'll pursue this later. # diff = difflib.ndiff(res, exp) # diff = list(diff) # for line in diff: # if line[:2] != ' ': # print string.strip(line) # ret = -1 # the following simple compare is fine for when the two data sets # (actual result vs. expected result) are equal, which should be true for # us. Unfortunately, if the test fails it's not nice at all. rl = len(res) el = len(exp) if el != rl: print 'Length of expected is %d, result is %d' % (el, rl) ret = -1 for i in range(min(el, rl)): if string.strip(res[i]) != string.strip(exp[i]): print '+:%s-:%s' % (res[i], exp[i]) ret = -1 if el > rl: for i in range(rl, el): print '-:%s' % exp[i] ret = -1 elif rl > el: for i in range (el, rl): print '+:%s' % res[i] ret = -1 return ret # Separate threads to handle stdout and stderr are created to run this function
def binput(outarray,fname,packtype=None,writetype='wb'): """ Unravels outarray and writes the data to a file, always in LittleEndian format, along with a header file containing the original data shape. Default is overwrite the destination file. Tries to figure out packtype from 4th-to-last character in filename. Thus, the routine understands these file formats ... 1bin=Int8, sbin=int16, ibin=Int32, fbin=Float32, dbin=Float64, etc. Usage: binput(outarray,filename,packtype=None,writetype='wb') """ if not packtype: packtype = fname[-4] # a speck of error checking if packtype == N.int16 and outarray.typecode() == 'f': # check to see if there's data loss if max(N.ravel(outarray)) > 32767 or min(N.ravel(outarray))<-32768: print "*** WARNING: CONVERTING FLOAT DATA TO OUT-OF RANGE int16 DATA" outdata = N.ravel(outarray).astype(packtype) # force the data on disk to be LittleEndian (for more efficient PC/Linux use) if not N.LittleEndian: outdata = outdata.byteswapped() outdata = outdata.tostring() outfile = open(fname,writetype) outfile.write(outdata) outfile.close() # Now, write the header file try: suffixindex = string.rfind(fname,'.') hdrname = fname[0:suffixindex+2]+'hdr' # include .s or .f or .1 or whatever except ValueError: hdrname = fname hdr = outarray.shape print hdrname outfile = open(hdrname,'w') outfile.write(pstat.list2string(hdr)) outfile.close() return None