• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python string.split函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: init2

def init2():
    global condor_sbin_path
    # try using condor commands to find it out
    try:
        condor_sbin_path=iexe_cmd("condor_config_val SBIN")[0][:-1] # remove trailing newline
    except ExeError,e:
        # try to find the RELEASE_DIR, and append bin
        try:
            release_path=iexe_cmd("condor_config_val RELEASE_DIR")
            condor_sbin_path=os.path.join(release_path[0][:-1],"sbin")
        except ExeError,e:
            # try condor_q in the path
            try:
                condora_sbin_path=iexe_cmd("which condor_advertise")
                condor_sbin_path=os.path.dirname(condora_sbin_path[0][:-1])
            except ExeError,e:
                # look for condor_config in /etc
                if os.environ.has_key("CONDOR_CONFIG"):
                    condor_config=os.environ["CONDOR_CONFIG"]
                else:
                    condor_config="/etc/condor/condor_config"

                try:
                    # BIN = <path>
                    bin_def=iexe_cmd('grep "^ *SBIN" %s'%condor_config)
                    condor_sbin_path=string.split(bin_def[0][:-1])[2]
                except ExeError, e:
                    try:
                        # RELEASE_DIR = <path>
                        release_def=iexe_cmd('grep "^ *RELEASE_DIR" %s'%condor_config)
                        condor_sbin_path=os.path.join(string.split(release_def[0][:-1])[2],"sbin")
                    except ExeError, e:
                        pass # don't know what else to try
开发者ID:Akel,项目名称:glideinWMS,代码行数:33,代码来源:condorExe.py


示例2: update

    def update(self, objfile):
        self.filename = objfile

        (sysname, nodename, release, version, machine) = os.uname()
        if sysname == "Linux":
            fp = os.popen("nm -P " + objfile, "r")
            symbols = map(self.split_, fp.readlines())
        elif sysname == "SunOS":
            fp = os.popen("nm -p " + objfile, "r")
            symbols = map(lambda l: string.split(l[12:]), fp.readlines())
            pass
        elif sysname == "IRIX":
            fp = os.popen("nm -B " + objfile, "r")
            symbols = map(lambda l: string.split(l[8:]), fp.readlines())
            pass

        object = objfile
        
        for (type, symbol) in symbols:
            if not self.objects.has_key(object):
                self.objects.update({ object : dict({ "exports" : dict(), "imports" : dict() }) })
                pass

            if type == "U":
                self.objects[object]["imports"].update({ symbol : dict() })
            elif type in ["C", "D", "T"]:
                self.objects[object]["exports"].update({ symbol : dict() })
                pass
            pass

        fp.close()
        return (None)
开发者ID:Amerekanets,项目名称:gimp,代码行数:32,代码来源:ns.py


示例3: readUNIPROTACC

def readUNIPROTACC():

    #
    # parse UniProt-to-InterPro associations via the UniProt/Acc file
    #
    # dictionary contains:
    #	key = uniprot id
    #   value = interpro id (IPR#####)
    #

    fp = open(uniprotFile,'r')

    for line in fp.readlines():
	tokens = string.split(line[:-1], '\t')
	key = tokens[0]

	# not all uniprot ids have interpro ids...
	if len(tokens[6]) == 0:
	    continue

	values = string.split(tokens[6], ',')

        if not uniprot_to_ip.has_key(key):
            uniprot_to_ip[key] = []
	for v in values:
	    uniprot_to_ip[key].append(v)

    fp.close()

    return 0
开发者ID:mgijax,项目名称:uniprotload,代码行数:30,代码来源:makeInterProAnnot.py


示例4: deg2HMS

def deg2HMS(ra='', dec='', round=False):
      import string
      RA, DEC= '', ''
      if dec:
          if string.count(str(dec),':')==2:
              dec00=string.split(dec,':')
              dec0,dec1,dec2=float(dec00[0]),float(dec00[1]),float(dec00[2])
              if '-' in str(dec0):       DEC=(-1)*((dec2/60.+dec1)/60.+((-1)*dec0))
              else:                      DEC=(dec2/60.+dec1)/60.+dec0
          else:
              if str(dec)[0]=='-':      dec0=(-1)*abs(int(dec))
              else:                     dec0=abs(int(dec))
              dec1=int((abs(dec)-abs(dec0))*(60))
              dec2=((((abs(dec))-abs(dec0))*60)-abs(dec1))*60
              DEC='00'[len(str(dec0)):]+str(dec0)+':'+'00'[len(str(dec1)):]+str(dec1)+':'+'00'[len(str(int(dec2))):]+str(dec2)
      if ra:
          if string.count(str(ra),':')==2:
              ra00=string.split(ra,':')
              ra0,ra1,ra2=float(ra00[0]),float(ra00[1]),float(ra00[2])
              RA=((ra2/60.+ra1)/60.+ra0)*15.
          else:
              ra0=int(ra/15.)
              ra1=int(((ra/15.)-ra0)*(60))
              ra2=((((ra/15.)-ra0)*60)-ra1)*60
              RA='00'[len(str(ra0)):]+str(ra0)+':'+'00'[len(str(ra1)):]+str(ra1)+':'+'00'[len(str(int(ra2))):]+str(ra2)
      if ra and dec:          return RA, DEC
      else:                   return RA or DEC
开发者ID:rkirkpatrick,项目名称:lcogtsnpipe,代码行数:27,代码来源:lscabsphotdef_old.py


示例5: dissassembleDBName

def dissassembleDBName(db):
    """Dissassemble the input db string.
    @type db: string
    @param db: input db string, e.g. [email protected]:3306:/var/log/mysql
    @rtype: tuple (dbName,dbHost,dbPort,dbSocket)
    @return: DB name, hostname of DB, its port and socket.
    """
    dbPort   = ""
    dbSocket = ""
    
    # check if db name doesn't have "%" character
    if string.find(db,"%")!=-1:
       raise "'%' is not allowed in DB name, if you'd like to specify port, please use ':' separator"

    # we need to parse db into dbName,dbHost,dbPort,dbSocket
    dbComponents = string.split(db,"@")
    if len(dbComponents)==2:
       dbName = dbComponents[0]
       content= string.split(dbComponents[1],":")
       dbHost = content[0]
       if len(content)>1 and content[1]:
          dbPort   = content[1]
       if len(content)==3 and content[2]:
          dbSocket = content[2]
    else:
       dbName = "EventStoreTMP"
       dbHost = dbComponents[0]
       dbPort = ""
       dbSocket = ""
    return (dbName,dbHost,dbPort,dbSocket)
开发者ID:JeffersonLab,项目名称:HDEventStore,代码行数:30,代码来源:esdb_auth.py


示例6: getClusterRecord

 def getClusterRecord(self, cl):
     #print 'in getClusterRecord'
     clRecList = []
     curList = []
     #curList gets list of conf info
     curInd = int(split(cl[0])[0])
     ctr = 1
     for l in cl:
         ll = split(l)
         #when built, newList is
         #[Rank,SubRank,Run,DockedEnergy,ClusterRMSD,RefREMSD]
         newList = map(lambda x:int(x),ll[:3])
         #3/29/05
         if self.wroteAll and self.version!=4.0:
             #print "setting run number to ", ctr
             newList[2] = ctr
             ctr = ctr + 1
         newList2 = map(lambda x:float(x),ll[3:-1])
         newList.extend(newList2)
         if newList[0]==curInd:
             curList.append(newList)
         else:
             clRecList.append(curList)
             curList = [newList]
             curInd = newList[0]
     clRecList.append(curList)
     self.clusterRecord = clRecList
开发者ID:marekolsak,项目名称:fastgrid,代码行数:27,代码来源:DlgParser.py


示例7: _getHeight

 def _getHeight(self):
     "splits into lines"
     self.comment1lines = string.split(self.comment1, "\n")
     self.codelines = string.split(self.code, "\n")
     self.comment2lines = string.split(self.comment2, "\n")
     textheight = len(self.comment1lines) + len(self.code) + len(self.comment2lines) + 18
     return max(textheight, self.drawHeight)
开发者ID:jameshickey,项目名称:ReportLab,代码行数:7,代码来源:test_pdfgen_general.py


示例8: convertVersionToInt

def convertVersionToInt(version): # Code par MulX en Bash, adapte en python par Tinou
    #rajouter pour les vesions de dev -> la version stable peut sortir
    #les personnes qui utilise la version de dev sont quand même informé d'une MAJ
    #ex 3.8.1 < 3.8.2-dev < 3.8.2
    print "Deprecated !"
    if("dev" in version or "beta" in version or "alpha" in version or "rc" in version):
        version = string.split(version,"-")
        version = version[0]
        versionDev = -5
    else:
        versionDev = 0

    version_s = string.split(version,".")
    #on fait des maths partie1 elever au cube et multiplier par 1000
    try:
        versionP1 = int(version_s[0])*int(version_s[0])*int(version_s[0])*1000
    except:
        versionP1 = 0
    try:
        versionP2 = int(version_s[1])*int(version_s[1])*100
    except:
        versionP2 = 0
    try:
        versionP3 = int(version_s[2])*10
    except:
        versionP3 = 0
    return(versionDev + versionP1 + versionP2 + versionP3)
开发者ID:PlayOnLinux,项目名称:POL-POM-4,代码行数:27,代码来源:playonlinux.py


示例9: getPrefix

def getPrefix(shortcut): # Get prefix name from shortcut
    if(os.path.isdir(os.environ["POL_USER_ROOT"]+"/shortcuts/"+shortcut)):
        return ""

    fichier = open(os.environ["POL_USER_ROOT"]+"/shortcuts/"+shortcut,'r').read()
    fichier = string.split(fichier,"\n")
    i = 0
    while(i < len(fichier)):
        if("export WINEPREFIX=" in fichier[i]):
            break
        i += 1

    try:
        prefix = string.split(fichier[i],"\"")
        prefix = prefix[1].replace("//","/")
        prefix = string.split(prefix,"/")

        if(os.environ["POL_OS"] == "Mac"):
            index_of_dotPOL = prefix.index("PlayOnMac")
            prefix = prefix[index_of_dotPOL + 2]
        else:
            index_of_dotPOL = prefix.index(".PlayOnLinux")
            prefix = prefix[index_of_dotPOL + 2]
    except:
        prefix = ""

    return prefix
开发者ID:PlayOnLinux,项目名称:POL-POM-4,代码行数:27,代码来源:playonlinux.py


示例10: get_setup

def get_setup():
    global image_directory
    file_name = image_directory + "setup.dat"

    try:
        f = open(file_name, "r")
    except ValueError:
        sys.exit("ERROR: golf_setup must be run before golf")

    # find limb
    s = string.split(f.readline())
    if len(s) >= 3:
        if s[2] == "left" or s[2] == "right":
            limb = s[2]
        else:
            sys.exit("ERROR: invalid limb in %s" % file_name)
    else:
        sys.exit("ERROR: missing limb in %s" % file_name)

    # find distance to table
    s = string.split(f.readline())
    if len(s) >= 3:
        try:
            distance = float(s[2])
        except ValueError:
            sys.exit("ERROR: invalid distance in %s" % file_name)
    else:
        sys.exit("ERROR: missing distance in %s" % file_name)

    return limb, distance
开发者ID:ncorwin,项目名称:baxter_pick_and_place,代码行数:30,代码来源:golf.py


示例11: decrypt

def decrypt(data, msgtype, servername, args):
  global decrypted
  hostmask, chanmsg = string.split(args, "PRIVMSG ", 1)
  channelname, message = string.split(chanmsg, " :", 1)
  if re.match(r'^\[\d{2}:\d{2}:\d{2}]\s', message):
    timestamp = message[:11]
    message = message[11:]
  else:
    timestamp = ''
  if channelname[0] == "#":
    username=channelname
  else:
    username, rest = string.split(hostmask, "!", 1)
    username = username[1:]
  nick = channelname.strip()
  if os.path.exists(weechat_dir + '/' + username + '.db'):
    a = Axolotl(nick, dbname=weechat_dir+'/'+username+'.db', dbpassphrase=getPasswd(username))
    a.loadState(nick, username)
    decrypted = a.decrypt(a2b_base64(message))
    a.saveState()
    del a
    if decrypted == "":
      return args
    decrypted = ''.join(c for c in decrypted if ord(c) > 31 or ord(c) == 9 or ord(c) == 2 or ord(c) == 3 or ord(c) == 15)
    return hostmask + "PRIVMSG " + channelname + " :" + chr(3) + "04" + weechat.config_get_plugin("message_indicator") + chr(15) + timestamp + decrypted
  else:
    return args
开发者ID:DarkDefender,项目名称:scripts,代码行数:27,代码来源:axolotl.py


示例12: WhereIs

 def WhereIs(file, path=None, pathext=None, reject=[]):
     if path is None:
         try:
             path = os.environ['PATH']
         except KeyError:
             return None
     if is_String(path):
         path = string.split(path, os.pathsep)
     if pathext is None:
         try:
             pathext = os.environ['PATHEXT']
         except KeyError:
             pathext = '.COM;.EXE;.BAT;.CMD'
     if is_String(pathext):
         pathext = string.split(pathext, os.pathsep)
     for ext in pathext:
         if string.lower(ext) == string.lower(file[-len(ext):]):
             pathext = ['']
             break
     if not is_List(reject) and not is_Tuple(reject):
         reject = [reject]
     for dir in path:
         f = os.path.join(dir, file)
         for ext in pathext:
             fext = f + ext
             if os.path.isfile(fext):
                 try:
                     reject.index(fext)
                 except ValueError:
                     return os.path.normpath(fext)
                 continue
     return None
开发者ID:datalogics-jeffh,项目名称:scons,代码行数:32,代码来源:Util.py


示例13: CheckFillFile

def CheckFillFile(fillfile):
    myfile=open(fillfile,'r').readlines()
    valid=True
    for r in myfile[1:]:
        temp=string.split(r)
        if len(temp)<3:
            valid=False
            print "Bad line '%s' in fillfile '%s':  not enough arguments"%(r,fillfile)
            return valid
        try:
            fill=string.atoi(temp[0])
        except:
            print "Bad line '%s' in fillfile '%s':  can't read fill # as an integer"%(r,fillfile)
            valid=False
            return valid
        try:
            runs=string.strip(temp[2])
            runs=string.split(runs,",")
            for run in runs:
                try:
                    string.atoi(run)
                except:
                    valid=False
                    print "Bad line '%s' in fillfile '%s':  can't parse runs"%(r,fillfile)
                    return valid
        except:
            print "Bad line '%s' in fillfile '%s':  can't ID runs"%(r,fillfile)
            valid=False
            return valid
    print "<CheckFillFile>  fill file '%s' appears to be formatted correctly!"%fillfile
    return valid
开发者ID:rodenm,项目名称:StoppedHSCP,代码行数:31,代码来源:pyGetFillScheme.py


示例14: getHMDBData

def getHMDBData(species):
    program_type,database_dir = unique.whatProgramIsThis()
    filename = database_dir+'/'+species+'/gene/HMDB.txt'

    x=0
    fn=filepath(filename)
    for line in open(fn,'rU').xreadlines():
        data = cleanUpLine(line)
        if x==0: x=1
        else:
            t = string.split(data,'\t')
            try: hmdb_id,symbol,description,secondary_id,iupac,cas_number,chebi_id,pubchem_compound_id,Pathways,ProteinNames = t
            except Exception:
                ### Bad Tab introduced from HMDB
                hmdb_id = t[0]; symbol = t[1]; ProteinNames = t[-1]
            symbol_hmdb_db[symbol]=hmdb_id
            hmdb_symbol_db[hmdb_id] = symbol
    
            ProteinNames=string.split(ProteinNames,',')
            ### Add gene-metabolite interactions to databases
            for protein_name in ProteinNames:
                try:
                    for ensembl in symbol_ensembl_db[protein_name]: 
                        z = InteractionInformation(hmdb_id,ensembl,'HMDB','Metabolic')
                        interaction_annotation_dbase[ensembl,hmdb_id] = z ### This is the interaction direction that is appropriate
                        try: interaction_db[hmdb_id][ensembl]=1
                        except KeyError: db = {ensembl:1}; interaction_db[hmdb_id] = db ###weight of 1 (weights currently not-supported)
                        try: interaction_db[ensembl][hmdb_id]=1
                        except KeyError: db = {hmdb_id:1}; interaction_db[ensembl] = db ###weight of 1 (weights currently not-supported)
                except Exception: None
开发者ID:wuxue,项目名称:altanalyze,代码行数:30,代码来源:InteractionBuilder.py


示例15: run

    def run(self):
        self.thread_running = True
        while self.thread_running:
            if self.thread_message == "get":
                try:
                    url = "http://mulx.playonlinux.com/wine/linux-i386/LIST"
                    req = urllib2.Request(url)
                    handle = urllib2.urlopen(req)
                    time.sleep(1)
                    available_versions = handle.read()
                    available_versions = string.split(available_versions, "\n")
                    self.i = 0
                    self.versions_ = []
                    while self.i < len(available_versions) - 1:
                        informations = string.split(available_versions[self.i], ";")
                        version = informations[1]
                        package = informations[0]
                        sha1sum = informations[2]
                        if not os.path.exists(Variables.playonlinux_rep + "/WineVersions/" + version):
                            self.versions_.append(version)
                        self.i += 1
                    self.versions_.reverse()
                    self.versions = self.versions_[:]

                    self.thread_message = "Ok"
                except:
                    time.sleep(1)
                    self.thread_message = "Err"
                    self.versions = ["Wine packages website is unavailable"]
            else:
                time.sleep(0.2)
开发者ID:PlayOnLinux,项目名称:PlayOnLinux_3,代码行数:31,代码来源:options.py


示例16: testObject

def testObject(test, obj, expect):
    contents = test.read(test.workpath('work1', obj))
    line1 = string.split(contents,'\n')[0]
    actual = string.join(string.split(line1))
    if not expect == actual:
        print "%s:  %s != %s\n" % (obj, repr(expect), repr(actual))
        test.fail_test()
开发者ID:datalogics-jeffh,项目名称:scons,代码行数:7,代码来源:gnutools.py


示例17: run

	def run(self):
		global STATUS
		while 1:
			data = ""
			try:
				sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				sock.connect((config.HDDTEMP_HOST, config.HDDTEMP_PORT))
				while 1:
					# give hddtemp time to send data
					d = sock.recv(1024)
					if (d == ""):
						break;
					data = data + d
			except socket.error, msg:
				print "Hddtemp_Thread could not connect to hddtemp daemon: %s" % msg
			else:
				if ((len(data)<3) or (data[0] != '|') or (data[len(data)-1] != '|')):
					print "Hddtemp_Thread received malformed data: %s" % data
				else:
					# data = |/dev/hdb|Maxtor 6Y120P0|41|C||/dev/hdc|Maxtor 6Y120P0|30|C|
					data = data[1:len(data)-1]
					# data = /dev/hdb|Maxtor 6Y120P0|41|C||/dev/hdc|Maxtor 6Y120P0|30|C
					list = string.split(data, '||')
					# data = "/dev/hdb|Maxtor 6Y120P0|41|C","/dev/hdc|Maxtor 6Y120P0|30|C"
					for i in range(len(list)):
						drive = string.split(list[i], '|')
						STATUS[drive[0]] = drive[2]
				sock.close()

			time.sleep(config.HDDTEMP_POLL)
开发者ID:flysurfer28,项目名称:mediacenter-overlay,代码行数:30,代码来源:idlebar_hddtemp.py


示例18: urlParse

	def urlParse(self, url):
		""" return path as list and query string as dictionary
			strip / from path
			ignore empty values in query string
			for example:
			if url is: /xyz?a1=&a2=0%3A1
			then result is: (['xyz'], { 'a2' : '0:1' } )
			if url is: /a/b/c/
			then result is: (['a', 'b', 'c'], None )
			if url is: /?
			then result is: ([], {} )
		"""
		x = string.split(url, '?')
		pathlist = filter(None, string.split(x[0], '/'))
		d = {}
		if len(x) > 1:
			q = x[-1]                  # eval query string
			x = string.split(q, '&')
			for kv in x:
				y = string.split(kv, '=')
				k = y[0]
				try:
					v = urllib.unquote_plus(y[1])
					if v:               # ignore empty values
						d[k] = v
				except:
					pass
		return (pathlist, d)
开发者ID:BackupTheBerlios,项目名称:websane-svn,代码行数:28,代码来源:websane.py


示例19: formatElement

def formatElement(el,path):
    if (el.find("{http://www.w3.org/2001/XMLSchema}annotation") is not None):
        splitPath=string.split(path,'/')
        #set default component to "scenario", i.e. write to the "Scenario" worksheet below
        component="scenario"
        printPath=string.replace(path,"/"+component,"")
        #update component if a know child element of scenario, i.e. write to another worksheet below
        if (len(splitPath)>2):
            if (splitPath[2] in worksheets):
                component=splitPath[2]
                printPath=string.replace(printPath,"/"+component,"")
        sheet= worksheets[component][0]
        row=worksheets[component][1]
        sheet.write(row,0,string.lstrip(printPath,"/"))
        annotation=el.find("{http://www.w3.org/2001/XMLSchema}annotation")
        docuElem=annotation.find("{http://www.w3.org/2001/XMLSchema}documentation")
        if (docuElem is not None):
            docu=docuElem.text
        else:
            docu="TODO"
        content=string.strip(docu)
        sheet.write(row,1,normalizeNewlines(content),docu_xf)
        appInfoElem=el.find("{http://www.w3.org/2001/XMLSchema}annotation").find("{http://www.w3.org/2001/XMLSchema}appinfo")
        if (appInfoElem is not None):
            appInfo=string.strip(appInfoElem.text)
        else:
            appInfo="name:TODO"
        appInfoList=string.split(appInfo,";")[0:-1]
        for keyValue in appInfoList:
            splitPair=string.split(keyValue,":")
            colIndex=appinfoOrder.index(string.strip(str(splitPair[0])))+2
            sheet.write(row,colIndex,splitPair[1],docu_xf)
        #update next row to be written in that sheet
        worksheets[component][1]=worksheets[component][1]+1
开发者ID:AenBleidd,项目名称:openmalaria,代码行数:34,代码来源:WriteParamDocu.py


示例20: process

def process(dataMatrix,samples, sample,genes, cancer,infile,flog, valuePOS, LOG2, maxLength):
    # one sample a file  
    fin=open(infile,'U')    
    fin.readline()
    for line in fin.readlines():
        data =string.split(line[:-1],"\t")
        hugo = data[0]
        value= data[valuePOS]
        hugo = string.split(hugo,"|")[0]

        if hugo=="?":
            hugo=data[0]

        if hugo not in genes:
            p=len(genes)
            genes[hugo]=p
            l=[]
            for j in range (0,maxLength):
                l.append("")    
            dataMatrix.append(l)
        
        if value not in ["","null","NULL","Null","NA"]:
            if LOG2:
                value = float(value)
                if value<0:
                    value = ""
                else:
                    value = math.log(float(value+1),2)

            x=genes[hugo]
            y=samples[sample]
            dataMatrix[x][y]=value
            
    fin.close()
    return 
开发者ID:jingchunzhu,项目名称:cgDataNew,代码行数:35,代码来源:RNAseq.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python string.splitfields函数代码示例发布时间:2022-05-27
下一篇:
Python string.rstrip函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap