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

Python regsub.gsub函数代码示例

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

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



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

示例1: test

def test():
	import sys
	import regsub
	args = sys.argv[1:]
	if not args:
		args = [
			'/etc/passwd',
			'file:/etc/passwd',
			'file://localhost/etc/passwd',
			'ftp://ftp.cwi.nl/etc/passwd',
			'gopher://gopher.cwi.nl/11/',
			'http://www.cwi.nl/index.html',
			]
	try:
		for url in args:
			print '-'*10, url, '-'*10
			fn, h = urlretrieve(url)
			print fn, h
			if h:
				print '======'
				for k in h.keys(): print k + ':', h[k]
				print '======'
			fp = open(fn, 'r')
			data = fp.read()
			del fp
			print regsub.gsub('\r', '', data)
			fn, h = None, None
		print '-'*40
	finally:
		urlcleanup()
开发者ID:nickzuck007,项目名称:python-bits,代码行数:30,代码来源:urllib.py


示例2: escape

def escape(s):
    """Replace special characters '&', '<' and '>' by SGML entities."""
    import regsub
    s = regsub.gsub("&", "&amp;", s)	# Must be done first!
    s = regsub.gsub("<", "&lt;", s)
    s = regsub.gsub(">", "&gt;", s)
    return s
开发者ID:asottile,项目名称:ancient-pythons,代码行数:7,代码来源:cgi.py


示例3: spew

def spew(clearol=0, clearul=0):
    global content, body, ollev, ullev

    if content:
        if entityprog.search(content) > -1:
            content = regsub.gsub('&', '&amp;', content)
            content = regsub.gsub('<', '&lt;', content)
            content = regsub.gsub('>', '&gt;', content)

        n = questionprog.match(content)
        if n > 0:
            content = '<em>' + content[n:] + '</em>'
            if ollev:                       # question reference in index
                fragid = regsub.gsub('^ +|\.? +$', '', secnum)
                content = '<a href="#%s">%s</a>' % (fragid, content)

        if element[0] == 'h':               # heading in the main text
            fragid = regsub.gsub('^ +|\.? +$', '', secnum)
            content = secnum + '<a name="%s">%s</a>' % (fragid, content)

        n = answerprog.match(content)
        if n > 0:                           # answer paragraph
            content = regsub.sub(sentprog, '<strong>\\1</strong>', content[n:])

        body.append('<' + element + '>' + content)
        body.append('</' + element + '>')
        content = ''

    while clearol and ollev: upol()
    if clearul and ullev: body.append('</ul>'); ullev = 0
开发者ID:Claruarius,项目名称:stblinux-2.6.37,代码行数:30,代码来源:faq2html.py


示例4: Main

def Main():
	form = FormContent()
	area = form["area"][0]
	spec = form["spec"][0]
	link = form["link"][0]
	url = form["url"][0]

	area = regsub.gsub(" ","_", area)
	spec = regsub.gsub(" ","_", spec)
	link = regsub.gsub(" ","_", link)
	url = regsub.gsub(" ","_", url)


	print 'Content-type: text/html \n\n'
	check = mydb.query("select * from mt101 where link = '"+url+"'").getresult()
	if len(check) > 0:
		delete = mydb.query("delete from mt101 where link = '"+url+"'")
		print "Deleted Old Entry"
	
	update = mydb.query("insert into mt101 values('"+area+"','"+spec+"','"+url+"','"+link+"')")		

	print '<HTML><HEAD>'
	print '<meta http-equiv="Refresh" content="1; URL='+url+'">'
	print '</HEAD><BODY BGCOLOR="white">'
	print 'Successfully entered'
开发者ID:akrherz,项目名称:pals,代码行数:25,代码来源:insert_link.py


示例5: _ctag

def _ctag(str, hrefs=()):
    """Quote, tag, and escape the text.

    This is a modified version of the 'ctag' function appearing in
    StructuredText.py. The differences include, 
      * it uses _split, so that it avoids escaping text in quotes or
      in math-mode.
      * it processes hrefs.
      * it escapes LaTeX special characters.
      * it doesn't try to find duplicate list items - that got moved
      into LaTeX.

    """
    if str is None: str = ''
    str = ' %s' % str			# prepend a space 
    str = _split(str)
    for i in xrange(len(str)): 
	if not i%2:
	    str[i]=regsub.gsub(quotable_re, '\\[email protected]\\[email protected]', str[i])
	    str[i]=regsub.gsub(slashable_re, '\\\\\\0', str[i])
	    str[i]=regsub.gsub(ST.strong,' {\\bfseries \\1}\\2', str[i])
	    str[i]=regsub.gsub(ST.em,' {\\itshape \\1}\\2',str[i])
	    for ref, link in hrefs:
		tag = '{\slshape %s}\\footnote{%s}' % (ref[1:-1], link)
		str[i] = string.joinfields(string.split(str[i], ref), tag)
    return string.joinfields(str)
开发者ID:HunterAllman,项目名称:kod,代码行数:26,代码来源:struct2latex.py


示例6: discover_panel_modules

    def discover_panel_modules(self):
        """Identify candidate panels.

        Return list of tuples describing found panel modules: (name,
        modname, moddir).

        Candidate modules must end in 'prefs.py' or 'prefs.pyc'.  The name
        is formed by extracting the prefix and substituting spaces for
        underscores (with leading and trailing spaces stripped).

        For multiple panels with the same name, the last one found is used."""
        got = {}
        for dir in panels_dirs:
            entries = []
            try:
                entries = os.listdir(dir)
            except os.error:
                # Optional dir not there.
                pass
            for entry in entries:
                if modname_matcher.match(entry) != -1:
                    name = regsub.gsub("_", " ", modname_matcher.group(1))
                    class_name = regsub.gsub("_", "",
                                             modname_matcher.group(1))
                    got[name] = ((string.strip(name), class_name, entry, dir))
        return got.values()
开发者ID:ashumeow,项目名称:grail,代码行数:26,代码来源:PrefsPanels.py


示例7: main

def main():
	metaHtmlFilename = "Quaero/web/quaero_meta.html"
	standardHtmlFilename = "Quaero/web/quaero.html"
	latex2htmlLogFilename = "Quaero/doc/manual/html.log"
	metaHtml = open(metaHtmlFilename,'r')
	standardHtml = open(standardHtmlFilename,'w')
	classified=0
	for line1 in metaHtml.readlines():
		keys = re.search("helpwindow_MANUAL\((.*)\)\.html",line1)
		if(not keys==None):
			key = keys.group(1)
			key = regsub.gsub("\+","\\+",key)
			latex2htmlLog = open(latex2htmlLogFilename,'r')
			foundNodeNumber = 0
			for line2 in latex2htmlLog.readlines():
				nodeNumber = re.search('"'+key+'" for node([0-9]*)\.html',line2)
				if(not nodeNumber==None):
					line1 = regsub.gsub("helpwindow_MANUAL("+key+").html","manual/manual/node"+nodeNumber.group(1)+".html",line1)
					foundNodeNumber = 1
			if(foundNodeNumber==0):
				print 'Key "'+key+'" not found.'
			latex2htmlLog.close()
		if regex.search("BeginClassified",line1) >= 0:
			classified=1
		if regex.search("EndClassified",line1) >= 0:
			classified=0
		if(classified==0):
			standardHtml.write(line1)
		if regex.search("</html>",line1) >= 0:
			break
	metaHtml.close()
	standardHtml.close()
开发者ID:YoungKwonJo,项目名称:usercode-1,代码行数:32,代码来源:updateHelpLinks.py


示例8: viewer

def viewer(): 
        if form.has_key("url"): 
                url = form["url"][0]
		urlloader(url)
	elif form.has_key("titleA"): 
                titleA = form["titleA"][0]
		titleA = regsub.gsub('_',' ', titleA)
		sloader(titleA)
	elif form.has_key("titleB"):
		titleB = form["titleB"][0]
		titleB = regsub.gsub('_',' ', titleB)
		floader(titleB)
	elif form.has_key("titleC"):
		titleC = form["titleC"][0]
		cloader(titleC)
	elif form.has_key("titleD"): 
		titleD = form["titleD"][0]
		loadertwo(titleD)
	elif form.has_key("titleE"): 
		titleE = form["titleE"][0]
		titler(titleE)
	elif form.has_key("title"):
		title = form["title"][0]
		titlertwo(title)
	elif form.has_key("search"): 
                blah = form["search"][0]
		sloader(blah)
	elif form.has_key("searchloc"): 
                save_search()
	elif form.has_key("saved"): 
                saved()

	else: 
		url = "/index.html"  
		startmain()
开发者ID:akrherz,项目名称:pals,代码行数:35,代码来源:index.py


示例9: processrawspec

	def processrawspec(self, raw):
		if self.whole.search(raw) < 0:
			self.report("Bad raw spec: %s", `raw`)
			return
		type, name, args = self.whole.group('type', 'name', 'args')
		type = regsub.gsub("\*", " ptr", type)
		type = regsub.gsub("[ \t]+", "_", type)
		if name in self.alreadydone:
			self.report("Name has already been defined: %s", `name`)
			return
		self.report("==> %s %s <==", type, name)
		if self.blacklisted(type, name):
			self.error("*** %s %s blacklisted", type, name)
			return
		returnlist = [(type, name, 'ReturnMode')]
		returnlist = self.repairarglist(name, returnlist)
		[(type, name, returnmode)] = returnlist
		arglist = self.extractarglist(args)
		arglist = self.repairarglist(name, arglist)
		if self.unmanageable(type, name, arglist):
			##for arg in arglist:
			##	self.report("    %s", `arg`)
			self.error("*** %s %s unmanageable", type, name)
			return
		self.alreadydone.append(name)
		self.generate(type, name, arglist)
开发者ID:asottile,项目名称:ancient-pythons,代码行数:26,代码来源:scantools.py


示例10: Main

def Main():
	form = cgi.FormContent()
	if not form.has_key("stations"):
		style.SendError("No station specified!")
	if not form.has_key("dataCols"):
		style.SendError("No data specified!")
	stations = form["stations"]
	dataCols = form["dataCols"]

	stationTables = map(addYear, stations)

	year = form["year"][0]
	startMonth = str( form["startMonth"][0] )
	startDay = str( form["startDay"][0] )
	endMonth = str( form["endMonth"][0] )
	endDay = str( form["endDay"][0] )
	timeType = form["timeType"][0]

	startTime = startMonth+"-"+startDay+"-"+year
	endTime = endMonth+"-"+endDay+"-"+year

	dataCols = tuple(dataCols)
	strDataCols =  str(dataCols)[1:-2]
        strDataCols = regsub.gsub("'", " ", strDataCols)


	if timeType == "hourly":
		mydb = pg.connect('campbellHourly', 'localhost', 5432)
		strDataCols = "date_part('year', day) AS year, date_part('month', day) AS month, date_part('day', day) AS day, date_part('hour', day) AS hour, "+strDataCols
	else:
		mydb = pg.connect('campbellDaily', 'localhost', 5432)
		strDataCols = "date_part('year', day) AS year, date_part('month', day) AS month, date_part('day', day) AS day, "+strDataCols


	print 'Content-type: text/plain \n\n'
	print """
# Output for Iowa Campbell Station Data
# Notes on the format of this data and units can be found at
#	http://www.pals.iastate.edu/campbell/info.txt
# If you have trouble getting the data you want, please send email to [email protected]

"""


	for stationTable in stationTables:
		queryStr = "SELECT day as sortday, '"+stationTable[:-5]+"' as statid, "+strDataCols+" from "+stationTable+" WHERE day >= '"+startTime+"' and day <= '"+endTime+"' ORDER by sortday ASC"
#		print queryStr
		results = mydb.query(queryStr)

		headings = results.listfields()[1:]
		strHeadings = str(tuple(headings))[1:-2]
	        strHeadings =  regsub.gsub("'", " ", strHeadings)
	        print  regsub.gsub(",", " ", strHeadings)
		
		results = results.getresult()
		printer(results, timeType)

		print "\n\n\n"

	print "#EOF"
开发者ID:akrherz,项目名称:pals,代码行数:60,代码来源:dataRequest.py


示例11: add_entry

def add_entry(ticks, comments, analysis, caseNum):
	comments = regsub.gsub("'","&#180;", comments)
	analysis = regsub.gsub("'","&#180;", analysis)

	thisDate = DateTime.gmtime(ticks)
        findDate = DateTime.ISO.strGMT(thisDate)

	delete = mydb.query("delete from annotations WHERE validtime = '"+findDate+"' and casenum = '"+caseNum+"' ") 	
	insert = mydb.query("insert into annotations (validtime, comments, analysis, casenum) values('"+findDate+"','"+comments+"','"+analysis+"','"+caseNum+"')")
	print 'DONE'
开发者ID:akrherz,项目名称:pals,代码行数:10,代码来源:addHourly.py


示例12: mungeFile

def mungeFile(file):
    # Read the file and modify it so that it can be bundled with the
    # other Pmw files.
    file = 'Pmw' + file + '.py'
    text = open(os.path.join(srcdir, file)).read()
    text = regsub.gsub('import Pmw\>', '', text)
    text = regsub.gsub('INITOPT = Pmw.INITOPT', '', text)
    text = regsub.gsub('\<Pmw\.', '', text)
    text = '\n' + ('#' * 70) + '\n' + '### File: ' + file + '\n' + text
    return text
开发者ID:JPLOpenSource,项目名称:SCA,代码行数:10,代码来源:bundlepmw.py


示例13: extractarg

	def extractarg(self, part):
		mode = "InMode"
		if self.asplit.match(part) < 0:
			self.error("Indecipherable argument: %s", `part`)
			return ("unknown", part, mode)
		type, name = self.asplit.group('type', 'name')
		type = regsub.gsub("\*", " ptr ", type)
		type = string.strip(type)
		type = regsub.gsub("[ \t]+", "_", type)
		return self.modifyarg(type, name, mode)
开发者ID:asottile,项目名称:ancient-pythons,代码行数:10,代码来源:scantools.py


示例14: psbars

 def psbars(self):
     psbits=regsub.gsub("1","I ",self.bits)
     psbits=regsub.gsub("0","O ",psbits)
     psbits=regsub.gsub("L","L ",psbits)
     linewidth=50
     p=0; j=linewidth; m=len(psbits); psbarlines=[]; blanks="^ | $"
     while p <= m:
         j = min(linewidth,m-p)
         psbarlines = psbarlines + [ regsub.gsub(blanks,"",psbits[p:p+j]) ]
         p=p+linewidth
     return [ "0 0 moveto" ] + psbarlines + [ "stroke" ]
开发者ID:OS2World,项目名称:APP-GRAPHICS-GNU_barcode,代码行数:11,代码来源:bookland.py


示例15: process

def process(fp, outfp, env = {}):
	lineno = 0
	while 1:
		line = fp.readline()
		if not line: break
		lineno = lineno + 1
		n = p_define.match(line)
		if n >= 0:
			# gobble up continuation lines
			while line[-2:] == '\\\n':
				nextline = fp.readline()
				if not nextline: break
				lineno = lineno + 1
				line = line + nextline
			name = p_define.group(1)
			body = line[n:]
			# replace ignored patterns by spaces
			for p in ignores:
				body = regsub.gsub(p, ' ', body)
			# replace char literals by ord(...)
			body = regsub.gsub(p_char, 'ord(\\0)', body)
			stmt = '%s = %s\n' % (name, string.strip(body))
			ok = 0
			try:
				exec stmt in env
			except:
				sys.stderr.write('Skipping: %s' % stmt)
			else:
				outfp.write(stmt)
		n =p_macro.match(line)
		if n >= 0:
			macro, arg = p_macro.group(1, 2)
			body = line[n:]
			for p in ignores:
				body = regsub.gsub(p, ' ', body)
			body = regsub.gsub(p_char, 'ord(\\0)', body)
			stmt = 'def %s(%s): return %s\n' % (macro, arg, body)
			try:
				exec stmt in env
			except:
				sys.stderr.write('Skipping: %s' % stmt)
			else:
				outfp.write(stmt)
		if p_include.match(line) >= 0:
			regs = p_include.regs
			a, b = regs[1]
			filename = line[a:b]
			if not filedict.has_key(filename):
				filedict[filename] = None
				outfp.write(
					'\n# Included from %s\n' % filename)
				inclfp = open('/usr/include/' + filename, 'r')
				process(inclfp, outfp, env)
开发者ID:asottile,项目名称:ancient-pythons,代码行数:53,代码来源:h2py.py


示例16: Main

def Main():
	print 'Content-type: text/html\n\n' 
        print '<HEADER>\n<TITLE>Entering message</TITLE>\n</HEADER>\n' 
        print '<BODY bgcolor="white">\n'

	form = FormContent()

	subject = form["subject"][0]
	name = form["name"][0]
	address = form["address"][0]
	description = form["description"][0]

	subject = regsub.gsub("'","&#180;",subject)
	name = regsub.gsub("'","&#180;",name)
	description = regsub.gsub("'","&#180;",description)

	if not form.has_key("subject"): SendError("You need to enter a subject") 
        if not form.has_key("name"): SendError("You should enter your name") 
        if not form.has_key("address"): SendError("What is your email address")
	if not form.has_key("description"): SendError("What is it's description")

	time = os.popen('date', 'r').read()

	enter = mydbase.query("INSERT INTO board VALUES('"+time+"','"+subject+"','"+name+"','"+address+"','"+description+"')")
	 
	print '<img src="../../images/pals_logo.gif" align=left>\n'
        print '<spacer type=vertical size="30">\n'
        print '<H1>PALS bulletin board</H1>\n'
        print '<a href="http://www.pals.iastate.edu/home/bboard.html">Add comment</a>'
	print '<BR CLEAR="all"><HR>'


        search = mydbase.query("select * from board")
        search = search.getresult()

        for i in range(len(search)):
                subject = search[i][1]
                name = search[i][2]
                address = search[i][3]
                description = search[i][4]
                date = search[i][0]
                date = date[4:10]+date[22:27]
                print "<P>\n<b>Subject:"
                print subject+'</b>'
                print "<BR>\n<dd>"
                print description
                print "<BR>\n"
                print '<P align="right">'
                print "( Posted by:"
                print '<A HREF="mailto:'+address+'" STYLE="color:blue">'+name+'</A>'
                print 'Posted on:'
                print date+')'
                print '</p><HR>'
开发者ID:akrherz,项目名称:pals,代码行数:53,代码来源:bblist.py


示例17: Main

def Main():
	print 'Content-type: text/html \n\n'
	print '<HTML><HEAD></HEAD><BODY BGCOLOR="white">'

	form = FormContent()
	area = form["area"][0]
	spec = form["spec"][0]

	area = regsub.gsub(" ","_", area)	
	spec = regsub.gsub(" ","_", spec)	

	html_content(area, spec)
开发者ID:akrherz,项目名称:pals,代码行数:12,代码来源:new_link.py


示例18: Main

def Main():
	print 'Content-type: text/html \n\n'
	form = cgi.FormContent()
	bNumber = form["bNumber"][0]
	bTime = regsub.gsub( " ", "+", form["bTime"][0])
	bTime = regsub.gsub( "_", " ", bTime)
	
	tableName = "t"+bTime[:4]+"_"+bTime[5:7]
	
	results = mydb.query("SELECT everything from "+tableName+" WHERE bTime = '"+bTime+"' and bNumber = '"+bNumber+"' ").dictresult()
	print '<PRE>'
	print regsub.gsub("\015\012", "", results[0]["everything"] )
	print '</PRE>'
开发者ID:akrherz,项目名称:pals,代码行数:13,代码来源:record.py


示例19: Main

def Main(): 
	form = FormContent()
	
	if not form.has_key("link"): style.SendError("Enter a Link")
	mylink = form["link"][0]
	mylink = regsub.gsub("'","&#180;",mylink)
	
	if not form.has_key("URL"): style.SendError("Enter an URL")
	myURL = form["URL"][0]

	if not form.has_key("description"): style.SendError("What is it's description")
	mydescription = form["description"][0]
	mydescription = regsub.gsub("'","&#180;",mydescription)

	style.header('Links Submitter','/images/ISU_bkgrnd.gif')

	mykindA = "null"
	mykindB = "null"
	mykindC = "null"
	mykindD = "null"

	if form.has_key("kindA"): mykindA = form["kindA"][0]
	if form.has_key("kindB"): mykindB = form["kindB"][0]
	if form.has_key("kindC"): mykindC = form["kindC"][0]
	if form.has_key("kindD"): mykindD = form["kindD"][0]

	mytime = os.popen('date', 'r').read()
	
	search = mydbase.query("select * from linkex where url = '"+myURL+"'")
	search = search.getresult()
	
	if len(search) > 0:
		style.std_top("URL already taken")
		sys.exit(0)
	
	search2 = mydbase.query("select * from linkex where link = '"+mylink+"'") 
        search2 = search2.getresult()

	if len(search2) > 0:
		style.std_top("Link title aready taken")
		sys.exit(0)
	
	enter = mydbase.query("INSERT INTO linkex VALUES( ' " + mylink+"','"+myURL+"','"+mykindA+"','"+mykindB+"','"+mykindC+"','"+mykindD+"','"+mydescription+"', '"+mytime+"')")
	
	style.std_top('Your link to "'+mylink+'" was saved!')
	print '<br><P>You can now:<ul>'
	print '<li><a href="http://www.pals.iastate.edu/cgi-bin/daryl_dev/printout.py">View all the links</a>'
	print '<li><a href="http://www.pals.iastate.edu/index.html">Go back to PALS Homepage</a>'	
	print '<spacer type="vertical" size="300">'
	style.std_bot()
开发者ID:akrherz,项目名称:pals,代码行数:50,代码来源:linksub.py


示例20: _split

def _split(s):
    """Split a string into normal and quoted pieces.

    Splits a string into normal and quoted (or math mode)
    sections. Returns a list where the even elements are normal
    text, and the odd elements are quoted. The appropiate quote
    tags ($ and \\verb) are applied to the quoted text.

    """
    r = []
    while 1:
	epos = eqn_re.search(s)
	qpos = ST.code.search(s)
	if epos == qpos:		## == -1
	    break
	elif (qpos == -1) or (epos != -1 and epos < qpos):
	    r.append(s[:epos])
	    end = epos + eqn_re.match(s[epos:])
	    arg = [eqn_re.group(1), eqn_re.group(3)]
	    if not arg[1]: arg[1] = ''
	    r.append( ' $%s$%s ' % tuple(arg))
	else:				## (epos==-1) or (qpos != -1 and epos > qpos):
	    r.append(s[:qpos])
	    end = qpos + ST.code.match(s[qpos:])
	    arg = [regsub.gsub(carrot_re, '^\\[email protected]\\[email protected]\\verb^', ST.code.group(1)),
		   ST.code.group(3)]
	    if not arg[1]: arg[1] = ''
	    r.append(' \\verb^%s^%s ' % tuple(arg))
	s = s[end:]
    r.append(s)
    return r
开发者ID:HunterAllman,项目名称:kod,代码行数:31,代码来源:struct2latex.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python api_reader.ApiReader类代码示例发布时间:2022-05-26
下一篇:
Python test_utils.get_db_connection函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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