当前位置: 首页>>代码示例>>Python>>正文


Python string.rfind函数代码示例

本文整理汇总了Python中string.rfind函数的典型用法代码示例。如果您正苦于以下问题:Python rfind函数的具体用法?Python rfind怎么用?Python rfind使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了rfind函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_contents

def process_contents(contents):
	global includePaths;
	includeFind = re.compile(r"^\s*#\s*include\s*\"([\w./\\]+)\"\s*$", re.MULTILINE)
	matchCount = 0
	pos = 0
	while (True):
		match = includeFind.search(contents, pos)
		if match == None:
			break;
		
		# print match.group(0), 
		
		value = match.group(1);
		valueStart = match.start(1)
		valueEnd = match.end(1)
		
		slash = string.rfind(value, "/");
		if slash != -1:
			value = value[slash + 1:]

		slash = string.rfind(value, "\\");
		if slash != -1:
			value = value[slash + 1:]
		
		if value in includePaths:
			contents = contents[:match.start(1)] + includePaths[value] + contents[match.end(1):];
			pos = match.start(1) + len(includePaths[value]) + 1;
			matchCount = matchCount + 1
		else:
			pos = match.end(0)
	
	# print contents;
	return (contents, matchCount);
开发者ID:abaradulkin,项目名称:dava.framework,代码行数:33,代码来源:fix_includes.py

示例2: rename

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)
        print fname, newname
        os.rename(fname, newname)
    return
开发者ID:eddienko,项目名称:SamPy,代码行数:30,代码来源:io.py

示例3: garbicat

 def garbicat(item0):
     p1 = string.find(item0, 'href="http://dmoz.org/')
     p2 = string.find(item0, '">')
     p3 = string.find(item0, '</a>')
     p4 = string.rfind(item0, '">')
     p5 = string.rfind(item0, '</a>')
     return item0[p1+21:p2], item0[p2+2:p3], item0[p4+2:p5]
开发者ID:codesyntax,项目名称:zOpenDirectory,代码行数:7,代码来源:px6.py

示例4: extract_filename

def extract_filename(path_filename):
    """extract filename right from slash"""
    if ac.app_windows == "no":
        filename = path_filename[string.rfind(path_filename, "/") + 1:]
    else:
        filename = path_filename[string.rfind(path_filename, "\\") + 1:]
    return filename
开发者ID:xpilgrim,项目名称:nautilus-scripts-audio-video,代码行数:7,代码来源:mp3_tagger.py

示例5: renamePicInPage

def renamePicInPage(fname, order=1):

    parser = pageParser()
    f = open(fname, 'r')
    parser.reset()
    parser.feed(f.read())
    parser.close()
    f.close()

    n = order
    for l in parser.links:

        if string.find(l, 'http://') >= 0:
            l = l[string.rfind(l, '/') : ]
            name = fname[ : string.rfind(fname, '.')]
            l = name + '_files' + l
            
        if os.access(l, os.F_OK):
            pos = string.rfind(l, '/')
            path = l[:pos]
            pos = string.rfind(l, '.')
            ext = l[pos:]
            name = '%s/p%03d%s' % (path, n, ext)
            n += 1
            print l, '-->', name
            os.rename(l, name)
开发者ID:github188,项目名称:homebrew,代码行数:26,代码来源:pdfmaker.py

示例6: time_string_to_core

def time_string_to_core(time):
    try:
        time=float(time)
        return time
    except:
        time=str(time)
    if(string.lower(time[-1])=='s'):
        return float(time[:-1])
    if(string.lower(time[-1])=='m'):
        return float(time[:-1])*60
    if(string.lower(time[-1])=='h'):
        return float(time[:-1])*60*60
    ftime=0.0
    multiple=1.0
    l=string.rfind(time, ':')
    while (l!=-1):
        n=float(time[l+1:])
        ftime=ftime+(n*multiple)
        time=time[:l]
        multiple=multiple*60.0
        if (multiple>3600):
            return None
        l=string.rfind(time, ':')
    if (len(time)):
        ftime=ftime+(float(time)*multiple)
    return ftime
开发者ID:inaugust,项目名称:lb,代码行数:26,代码来源:attribute_widgets.py

示例7: __init__

    def __init__(self, fields):

	if len(fields) != 6:
	    raise "Netstat Parse Error", "tcp class requires 6 fields, not %d" % (len(fields))

	# local address
	dot = string.rfind(fields[3], '.')
	if dot == -1:
	    raise "Netstat Parse Error", "tcp, expected '<ip>.<port>', found '%s'" % (fields[3])
	self.local_addr_ip = fields[3][:dot]
	self.local_addr_port = fields[3][dot+1:]

	# remote address
	dot = string.rfind(fields[4], '.')
	if dot == -1:
	    raise "Netstat Parse Error", "tcp, expected '<ip>.<port>', found '%s'" % (fields[4])
	self.remote_addr_ip = fields[4][:dot]
	self.remote_addr_port = fields[4][dot+1:]

	# send queue size
	self.send_queue = int(fields[2])

	# receive queue size
	self.receive_queue = int(fields[1])

	# state
	self.state = fields[5]
开发者ID:hexdump42,项目名称:eddie-tool,代码行数:27,代码来源:netstat.py

示例8: load_directory

    def load_directory(self, path):

        resource.path.append(path)
        print resource.path
        osPath = ''
        for _ in resource.path:
            osPath += _
            osPath += os.sep
        osPath = osPath[:-1]
        print osPath
        dirList = os.listdir(osPath)
            
        print "Entering directory %s.\n" % path
        resource.reindex()
        for fname in dirList:
            ext = ''
            print fname
            if string.rfind(fname,".") != -1:
                name = fname[:string.rfind(fname,".")]
                ext = fname[string.rfind(fname,"."):]
            else:
                name = fname
            print "name = %s" % name
            print "ext = %s" % ext
            if ( ext ) and (ext in self.filetypes):
                self.load_file(name, ext, osPath)
            if not ext:
                self.load_directory(name)
        print "Leaving directory %s.\n" % resource.path.pop()
开发者ID:DMAshura,项目名称:porcupyne,代码行数:29,代码来源:resources.py

示例9: addEvent

    def addEvent(self, event):
        title = event.name 
        try:
            content = getDescription(event.link)
        except Exception:
            pass
        where = event.place + ", Windsor, Ontario"

        start_time = [0, 0, 0, 0, 0, 0, 0, 0, -1]
        start_time[0] = int(event.date[string.rfind(event.date,'/')+1:])
        start_time[1] = int(event.date[:string.find(event.date,'/')])
        start_time[2] = int(event.date[string.find(event.date,'/')+1:string.rfind(event.date,'/')])
        start_time[3] = int(event.time[:string.find(event.time,':')])
        if (event.time[-2:] == "PM"):
            start_time[3] += 12
        start_time[4] = int(event.time[string.find(event.time,':')+1:-3])
        
        end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.localtime(time.mktime(tuple(start_time)) + 7200 + DEFAULT_TIME_OFFSET * 3600))
        start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.localtime(time.mktime(tuple(start_time)) + DEFAULT_TIME_OFFSET * 3600))

        cevent = gdata.calendar.CalendarEventEntry()
        cevent.title = atom.Title(text=title)
        cevent.content = atom.Content(text=content)
        cevent.where.append(gdata.calendar.Where(value_string=where))
        cevent.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))

        feed = self.chrysler_cal.GetAlternateLink().href[21:]
        new_event = self.cal_client.InsertEvent(cevent, feed)
        print "Added event" , title , "at" , event.time , event.date
开发者ID:apetresc,项目名称:Codebook,代码行数:29,代码来源:chrysler.py

示例10: get_docs

def get_docs(code):
    # Get list of links that match
    # <a href="(/people/.*?\.(pdf|doc|jpg|docx|zip)?)"
    if code:
        docs = re.findall(LOCAL_DOC_TAG_PATTERN, code)
        for doc in docs:
            # Clean up URL
            doc_path = doc[0].replace(' ', '%20')
            doc_url = 'http://www.sjsu.edu' + doc_path
            output_dir = fix_name(doc_path[1:string.rfind(doc_path, '/')])
            # Change file name back to match link
            file_name = doc_path[string.rfind(doc_path, '/') + 1:].replace('%20', ' ')
            logging.info("reading file: " + file_name)
            # logging.info("urlencoded name: " + urllib.quote_plus(file_name))
            # print "encoded name: " + file_name.encode('utf-8')
            
            # Create directory if necessary
            if not os.path.exists(output_dir):
                logging.info( "Creating dir " + output_dir)
                os.makedirs(output_dir)
                    
            try:
                remote = urllib2.urlopen(doc_url)
                # output_path = output_dir + '/' + file_name)
                output_path = output_dir + '/' + urllib.quote_plus(file_name)
                output_path = output_path.replace('+', ' ')
                logging.info( "Writing " + output_path )
                local_doc = open(output_path, 'w+')
                local_doc.write(remote.read())
                local_doc.close()
            except Exception as err:
                error_message = str(err.args)
                logging.error( "Error: " + error_message + ' in ' + file_name )
    else:
        print "code is empty"
开发者ID:scot-work,项目名称:website-builder-migration,代码行数:35,代码来源:migrate.py

示例11: main

def main(argv):
  
	handle = ilu.LookupObject("relocate-server", "dummy", relocate.Foo)
	handle_sbh = handle.IluSBH()
	print 'sbh of handle is', handle_sbh
	cinfo = string.rfind(handle_sbh, ';')
	if cinfo < 0:
		print "can't find cinfo of dummy object in sbh <" + handle_sbh + "!"
		sys.exit(1)
	handle_cinfo = handle_sbh[cinfo+1:]
	if not handle:
		print "Can't find dummy"
		sys.exit(2)
	newobj = handle.dummy()
	newobj_sbh = newobj.IluSBH()
	print 'sbh of new obj is', newobj_sbh
	cinfo = string.rfind(newobj_sbh, ';')
	if cinfo < 0:
		print "can't find cinfo of dummy object in sbh <" + newobj_sbh + "!"
		sys.exit(1)
	newobj_cinfo = newobj_sbh[cinfo+1:]
	if (newobj_cinfo != handle_cinfo):
		print 'different cinfos!'
		sys.exit(1)
	sys.exit(0)
开发者ID:spchamp,项目名称:ilu,代码行数:25,代码来源:client.py

示例12: nmapScanUpload

def nmapScanUpload():
    print 'Nmap Scan & Upload'
    ipToScan = getPrivateIP()
    #Generates the ip address that can be fed into the nmap command. This simple replaces the 4th octet with a 0 and appends a /24 to scan the class C subnet.
    ipToScan = ipToScan[:string.rfind(ipToScan, '.') + 1] + '0/24'
    index = string.rfind(ipToScan, '.')
    print index
    print ipToScan
    #Starts the bridge interface and sets the display.
    nmapScan = subprocess.Popen('nmap ' + ipToScan + ' -oN nmapoutput.txt', shell=True, stderr=PIPE)
    lcd.backlight(lcd.GREEN)
    lcd.clear()
    lcd.message("Running\nNmap Scan")
    error = nmapScan.communicate()
    errorCheck(error, 'NMAP\nFailed', 'Scan\nComplete')
    lcd.clear()
    lcd.message("Scan\nComplete")
    sleep(1)
    lcd.clear()
    lcd.message("Uploading\nFile")
    #Starts FTP session
    ftpSession = ftplib.FTP(ftp_server, ftp_username, ftp_password)
    ftpSession.cwd('nmap')
    #Opens file to be uploaded
    file = open('nmapoutput.txt', 'rb')
    #Uploads the File
    ftpSession.storbinary('STOR nmapoutput.txt', file)
    file.close()
    ftpSession.quit()
    lcd.clear()
    lcd.message("Upload\nSuccessful")
    sleep(3)
    funtionBreak()
开发者ID:Zero1-Nation,项目名称:Slypi,代码行数:33,代码来源:slypi.py

示例13: __init__

    def __init__(self,similarity_table,unordered_filelist, list_of_files):

        self._list_of_files = list_of_files

        #given as parameter, this is result of document representation
        self.table=similarity_table

        #the clusters are represented as regular expressions
        #final regular expression is the string representation of cluster_list
        self.cluster_list = list()

        #a cluster is represented as [[1,2],3]
        #all the hierarchy that group at a certain level is maintained in this cluster_dict
        #this keeps height as key and cluster formed at that hieght as its value
        self.cluster_dict = dict()

        #contains the indexed filenames
        #each filename is given a particular id
        self.unordered_filelist = unordered_filelist

        #contains the classes we have in our dataset
        self.classes = list()
        for name in self.unordered_filelist:
            cls = name[:rfind(name, "/")]
            cls = cls[rfind(cls, "/")+1:]
            if cls not in self.classes:
                self.classes.append(cls)
        self.class_count = len(self.classes)
开发者ID:mdanishs,项目名称:documentclustering,代码行数:28,代码来源:Algorithm.py

示例14: __parseCTypedefMemberdef

	def __parseCTypedefMemberdef(self, node):
		name = node.find('./name').text
		definition = node.find('./definition').text
		if string.find(definition, 'typedef ') == 0:
			definition = definition[8 :]
		if string.rfind(name, 'Cb') == len(name) - 2:
			pos = string.find(definition, "(*")
			if pos == -1:
				return None
			returntype = definition[0:pos].strip()
			if returntype != "void":
				return None
			returnarg = CArgument(returntype, enums = self.enums, structs = self.__structs)
			definition = definition[pos + 2 :]
			pos = string.find(definition, "(")
			definition = definition[pos + 1 : -1]
			argslist = CArgumentsList()
			for argdef in definition.split(', '):
				argType = ''
				starPos = string.rfind(argdef, '*')
				spacePos = string.rfind(argdef, ' ')
				if starPos != -1:
					argType = argdef[0 : starPos + 1]
					argName = argdef[starPos + 1 :]
				elif spacePos != -1:
					argType = argdef[0 : spacePos]
					argName = argdef[spacePos + 1 :]
				argslist.addArgument(CArgument(argType, argName, self.enums, self.__structs))
			if len(argslist) > 0:
				paramdescs = node.findall("detaileddescription/para/parameterlist[@kind='param']/parameteritem")
				if paramdescs:
					for arg in argslist.arguments:
						for paramdesc in paramdescs:
							if arg.name == paramdesc.find('./parameternamelist').find('./parametername').text:
								arg.description = self.__cleanDescription(paramdesc.find('./parameterdescription'))
					missingDocWarning = ''
					for arg in argslist.arguments:
						if arg.description == None:
							missingDocWarning += "\t'" + arg.name + "' parameter not documented\n";
					if missingDocWarning != '':
						print(name + ":\n" + missingDocWarning)
			f = CEvent(name, returnarg, argslist)
			deprecatedNode = node.find(".//xrefsect[xreftitle='Deprecated']")
			if deprecatedNode is not None:
				f.deprecated = True
			f.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()
			f.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))
			return f
		else:
			pos = string.rfind(definition, " " + name)
			if pos != -1:
				definition = definition[0 : pos]
			td = CTypedef(name, definition)
			deprecatedNode = node.find(".//xrefsect[xreftitle='Deprecated']")
			if deprecatedNode is not None:
				td.deprecated = True
			td.briefDescription = ''.join(node.find('./briefdescription').itertext()).strip()
			td.detailedDescription = self.__cleanDescription(node.find('./detaileddescription'))
			return td
		return None
开发者ID:Gui13,项目名称:linphone,代码行数:60,代码来源:genapixml.py

示例15: item_rename

def item_rename(request, op):
  """ Namen des Objektes aendern """
  item_container = get_my_item_container(request, op)
  if item_container.is_changeable:
    if request.GET.has_key('new_name') :
      is_folderish = item_container.item.app.is_folderish
      app_name = item_container.item.app.name
      # --- muss eventuell .html ergaenzt werden?
      check_this_name = is_folderish or is_file_type(app_name)
      new_name = check_name(request.GET['new_name'], check_this_name)
      # --- Gibt es schon in Objekt mit dem gewuenschten Namen?
      parent = item_container.get_parent()
      if parent != None and exist_item(parent, new_name):
        transaction.commit()
        return show_error_object_exist(request, item_container, new_name)
      if is_file_type(app_name):
        old_path = get_file_path(item_container)
        new_path = old_path[:string.rfind(old_path,'/')+1] + new_name
        os.rename(old_path, new_path)
      # --- Aenderungen vornehmen
      if is_folderish:
        n_pos = 1 + string.rfind(item_container.container.path[:-1], '/')
        new_path = item_container.container.path[:n_pos] + new_name +'/'
        old_path = item_container.container.path
        change_container_path(old_path, new_path)
      item_container.item.name = new_name
      item_container.item.save()
  transaction.commit()
  parent = item_container.get_parent()
  path = get_site_url(parent, 'index.html/manage/')
  return HttpResponseRedirect(path)
开发者ID:shagun30,项目名称:djambala-2,代码行数:31,代码来源:views_clipboard.py


注:本文中的string.rfind函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。