本文整理汇总了Python中string.split函数的典型用法代码示例。如果您正苦于以下问题:Python split函数的具体用法?Python split怎么用?Python split使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了split函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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
示例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
示例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
示例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
示例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)