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


Python Formatter类代码示例

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


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

示例1: get

	def get(self,format,id):
		#set content-type
		self.response.headers['Content-Type'] = Formatter.contentType(format)
		
		#get consumer/client app id
		appid = 'Unknown'
		if (self.request.GET):
			if ('appid' in self.request.GET):
				appid = self.request.GET['appid']
			if ('app' in self.request.GET):
				appid = self.request.GET['app']
		
		referer = ''
		if ('HTTP_REFERER' in os.environ):
			referer = os.environ['HTTP_REFERER']
		
		returnData = APIContent.getHackerNewsPost(id,format,self.request.url, referer, self.request.remote_addr)
			
		#track this request
		GAHelper.trackGARequests('/post/%s' % (id), appid, referer)
		
		if (not returnData):
			returnData = ''
		
		#output to the browser
		self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
开发者ID:dotkwame,项目名称:Hacker-News-Droid-API,代码行数:26,代码来源:GetHNPostHandler.py

示例2: main

def main():

	f = open('data/person_foaf.n3')
	fresnel_data = f.read()
	fresnel = Fresnel( fresnel_data )
	print "Created Fresnel Graph.."
	rdf_graph = Graph()
	print "Downloading resource.."
	#f = open('data/Tim_Berners-Lee.rdf')
	#rdf_graph.parse( file=f, format="xml")
	#rdf_graph.parse(source="http://dbpedia.org/page/A._P._J._Abdul_Kalam")
	#print "more..."
	
	f = open('data/A._P._J._Abdul_Kalam.rdf')
	rdf_graph.parse( file=f, format="xml")
	#rdf_graph.parse(source="http://dbpedia.org/page/Tim_Berners-Lee")
	for term in rdf_graph:
		print term
	print "Making selection.."
	selector = Selector( fresnel , rdf_graph)
	selector.select()
	formatter = Formatter( selector )
	formatter.format()
	data = "<html>\n<head><link rel='stylesheet' type='text/css' href='style.css'></head>\n<body>\n" 
	for resource in formatter.result:
		print resource.render()
		data += resource.render()
	data += "</body>\n</html>"
	f = open('output/test.html', 'w')
	f.write(data.encode('utf-8'))
开发者ID:Cookielabs,项目名称:panorama,代码行数:30,代码来源:main.py

示例3: getDiagnosisICD9Data

	def getDiagnosisICD9Data(self,xml,format):
		if (xml):
			documentElms = xml.getElementsByTagName('entry')
			if (documentElms):
				#grab two highest ranked content
				content1 = ''
				content2 = ''
				
				contentNode1 = documentElms[0]
				content1 = APIUtils.parseHealthDiagnosisICD9Content(format,contentNode1)
				
				if (len(documentElms) > 0):
					contentNode2 = documentElms[1]
					content2 = APIUtils.parseHealthDiagnosisICD9Content(format,contentNode2)
				
				returnData = "%s%s" % (content1, content2)
				if (format == 'json'):
					return returnData[:-1]
				else:
					return returnData		
			else:
				logging.error('unable to retrieve diagnosis content')
				return Formatter.data(format, 'error', 'No results')
		else:
			logging.error('unable to retrieve diagnosis content')
			return Formatter.data(format, 'error', 'Unable to retrieve content from provider')
开发者ID:,项目名称:,代码行数:26,代码来源:

示例4: getHealthNews

def getHealthNews(lan='en',format='json'):
	returnData = MutableString()
	returnData = ''
	if (lan == 'es'):
		dom = minidom.parse(urllib.urlopen(AppConfig.medlinePlusHealthNewsSpanishURL))
	else:
		dom = minidom.parse(urllib.urlopen(AppConfig.medlinePlusHealthNewsEnglishURL))
	rssTitle = MutableString()
	rssDescription = MutableString()
	rssURL = MutableString()
	for node in dom.getElementsByTagName('item'):
		for item_node in node.childNodes:
			rssTitle = ''
			rssDescription = ''
			rssURL = ''
			#item title
			if (item_node.nodeName == "title"):
				for text_node in item_node.childNodes:
					if (text_node.nodeType == node.TEXT_NODE):
						rssTitle += text_node.nodeValue
			#description
			if (item_node.nodeName == "description"):
				for text_node in item_node.childNodes:
					rssDescription += text_node.nodeValue
			#link to URL
			if (item_node.nodeName == "link"):
				for text_node in item_node.childNodes:
					rssURL += text_node.nodeValue
			
			if (format == 'json'):
				startTag = '{'
				endTag = '},'
				
				#cleanup
				#rssTitle = re.sub("\"", "'", rssTitle)
				rssTitle = re.sub("\n", "", rssTitle)
				rssTitle = re.sub("\"", "\\\"", rssTitle)
				rssDescription = re.sub("\"", "\\\"", rssDescription)
				rssDescription = re.sub("\n", "", rssDescription)
				rssDescription = re.sub("\t", " ", rssDescription)
				rssDescription = re.sub("\r", "", rssDescription)
				
				if (len(rssDescription) > 0):
					rssDescription = Formatter.data(format, 'description', escape(rssDescription))[:-1]
			else:
				startTag = '<record>'
				endTag = '</record>'		
				if (len(rssDescription) > 0):
					rssDescription = Formatter.data(format, 'description', escape(rssDescription))								
			
			if (len(rssTitle) > 0):
				returnData += startTag + Formatter.data(format, 'title', rssTitle)
				
			if (len(rssURL) > 0):
				returnData += Formatter.data(format, 'url', rssURL) 
			
			if (len(rssDescription) > 0 ):
				returnData += rssDescription + endTag
	
	return returnData
开发者ID:,项目名称:,代码行数:60,代码来源:

示例5: get

	def get(self,keyword, state, format='json'):
		#set content-type
		self.response.headers['Content-Type'] = Formatter.contentType(format)
		
		returnData = MutableString()
		returnData = ''
		try:
			#get XML from the service
			state = "%s%s" % ("NA%3AUS%3A", state)
			xml = minidom.parse(urllib.urlopen('%s&term=%s&state1=%s' % (AppConfig.clinicalTrialsAPIURL, keyword, state.upper())))
			if (xml):
				documentElms = xml.getElementsByTagName('clinical_study')
				if (documentElms):
					for docNode in documentElms:
						content = APIUtils.parseClinicalTrialsContent(format,docNode)
						returnData += content
							
				else:
					logging.error('unable to retrieve content')
					self.response.out.write(Formatter.error(format, 'No results'))
					return
			else:
				logging.error('unable to retrieve content')
				self.response.out.write(Formatter.error(format, 'Unable to retrieve content from provider'))
				return
					
		except Exception, e:
			logging.error('GetClinicalTrialsHandler: unable to get health topics or parse XML: %s' % e)
			self.response.out.write(Formatter.error(format, 'Exception: %s' % (e)))
			return
开发者ID:,项目名称:,代码行数:30,代码来源:

示例6: constructFromFile

 def constructFromFile(self):
     self.constructNewBoard()
     try:
         self.file = FileUtil.openForRead(os.path.join(FileUtil.getProgramDirectory(), "maps", self.mapName + ".battlefield"))
     except IOError:
         print "Error loading map"
     ships = Formatter.stripShips(Formatter.convertMatrix(self.file))
     self.board.addShips(ships)
开发者ID:Dummyc0m,项目名称:BattleShip,代码行数:8,代码来源:Game.py

示例7: get

    def get(self, format='json'):
        #set content-type
        self.response.headers['Content-Type'] = Formatter.contentType(format)

        returnData = MutableString()
        returnData = APIContent.getHackerNewsRSS(format)

        referer = ''
        if ('HTTP_REFERER' in os.environ):
            referer = os.environ['HTTP_REFERER']

        #track this request
        GAHelper.trackGARequests('/rss', self.request.remote_addr, referer)

        #output to the browser
        self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
开发者ID:abuggia,项目名称:Hacker-News-Droid-API,代码行数:16,代码来源:GetHNRSSHandler.py

示例8: post

	def post(self):
		#set content-type		
		format = "json"
		formatParamName = "format"
		if (formatParamName in self.request.params):
			format = self.request.params[formatParamName]
		
		self.response.headers['Content-Type'] = Formatter.contentType(format)
		
		#get content
		textToTranslate = ""
		textParamName = "data"
		if (textParamName in self.request.params):
			textToTranslate = self.request.params[textParamName]
		
		if (textToTranslate == None or textToTranslate == ''):
			logging.error('GetTranslateHandler: invalid parameters')
			self.response.out.write(Formatter.error(format, 'Invalid parameters'))
			return
		
		#strip tags?
		stripTagsParam = "striphtml"
		if (stripTagsParam in self.request.params):
			if (self.request.params[stripTagsParam] == 'true'):
				textToTranslate = CharReplacementMap.remove_html_tags(textToTranslate)
		
		#language
		toLanguage = "es"
		lanParam = "language"
		if (textParamName in self.request.params):
			toLanguage = self.request.params[lanParam]
		
		#auto-detect language (blank)
		sourceLanguage = ''
		params = ({'langpair': '%s|%s' % (sourceLanguage, toLanguage), 'v': '1.0' })
		returnData = MutableString()
		translatedText = '' 
		for textToTranslate in self.getSplits(textToTranslate): 
			params['q'] = textToTranslate 
			resp = simplejson.load(urllib.urlopen('%s' % (AppConfig.googleTranslateAPIURL), data = urllib.urlencode(params))) 
			try:
				translatedText += resp['responseData']['translatedText']
			except Exception, e:
				logging.error('GetTranslateHandler: error(s) translating data: %s' % e)
				self.response.out.write(Formatter.error(format, 'Exception: %s' % (e)))
				return
开发者ID:,项目名称:,代码行数:46,代码来源:

示例9: get

    def get(self, format='json', limit=1):
        #set content-type
        self.response.headers['Content-Type'] = Formatter.contentType(format)

        referer = ''
        if ('HTTP_REFERER' in os.environ):
            referer = os.environ['HTTP_REFERER']

        returnData = APIContent.getHackerNewsLatestContent('', format, self.request.url, referer, self.request.remote_addr, limit)

        #track this request
        GAHelper.trackGARequests('/latest', self.request.remote_addr, referer)

        if (not returnData):
            returnData = ''

        #output to the browser
        self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
开发者ID:abuggia,项目名称:Hacker-News-Droid-API,代码行数:18,代码来源:GetHNLatestHandler.py

示例10: get

	def get(self,format,user):
		#set content-type
		self.response.headers['Content-Type'] = Formatter.contentType(format)
		
		referer = ''
		if ('HTTP_REFERER' in os.environ):
			referer = os.environ['HTTP_REFERER']
		
		returnData = APIContent.getHackerNewsSubmittedContent(user,format,self.request.url, referer, self.request.remote_addr)
			
		#track this request
		GAHelper.trackGARequests('/submitted/%s' % (user), self.request.remote_addr, referer)
		
		if (not returnData):
			returnData = ''
		
		#output to the browser
		self.response.out.write(Formatter.dataWrapper(format, returnData))
开发者ID:jackfranklin,项目名称:Hacker-News-Droid-API,代码行数:18,代码来源:GetHNSubmittedHandler.py

示例11: get

    def get(self, format='json', page=''):
        #set content-type
        self.response.headers['Content-Type'] = Formatter.contentType(format)

        referer = ''
        if ('HTTP_REFERER' in os.environ):
            referer = os.environ['HTTP_REFERER']

        returnData = APIContent.getHackerNewsNewestContent(page, format, self.request.url, referer, self.request.remote_addr)
        if (not returnData or returnData == None or returnData == '' or returnData == 'None'):
            #call the service again this time without the pageID
            returnData = APIContent.getHackerNewsNewestContent('', format, self.request.url, referer, self.request.remote_addr)

        #track this request
        GAHelper.trackGARequests('/newest', self.request.remote_addr, referer)

        #output to the browser
        self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get('callback')))
开发者ID:abuggia,项目名称:Hacker-News-Droid-API,代码行数:18,代码来源:GetHNNewestHandler.py

示例12: man

    def man(self, pattern):
        """Call viewer.sh to view man page"""
        try:
            os.makedirs(Environ.man_dir)
        except:
            pass

        avail = os.listdir(Environ.man_dir)

        if not os.path.exists(Environ.index_db):
            raise RuntimeError("can't find index.db")

        conn = sqlite3.connect(Environ.index_db)
        cursor = conn.cursor()

        # Try direct match
        try:
            page_name, url = cursor.execute(
                "SELECT name,url FROM CPPMAN WHERE" ' name="%s" ORDER BY LENGTH(name)' % pattern
            ).fetchone()
        except TypeError:
            # Try standard library
            try:
                page_name, url = cursor.execute(
                    "SELECT name,url FROM CPPMAN" ' WHERE name="std::%s" ORDER BY LENGTH(name)' % pattern
                ).fetchone()
            except TypeError:
                try:
                    page_name, url = cursor.execute(
                        "SELECT name,url FROM " 'CPPMAN WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)' % pattern
                    ).fetchone()
                except TypeError:
                    raise RuntimeError("No manual entry for " + pattern)
        finally:
            conn.close()

        page_name = page_name.replace("/", "_")
        if page_name + ".3.gz" not in avail or self.forced:
            self.cache_man_page(url, page_name)
            self.update_mandb()

        pager = Environ.pager if sys.stdout.isatty() else Environ.renderer

        # Call viewer
        pid = os.fork()
        if pid == 0:
            os.execl(
                "/bin/sh",
                "/bin/sh",
                pager,
                Environ.man_dir + page_name + ".3.gz",
                str(Formatter.get_width()),
                Environ.pager_config,
                page_name,
            )
        return pid
开发者ID:Mondego,项目名称:pyreco,代码行数:56,代码来源:allPythonContent.py

示例13: get

    def get(self, format, user):
        # set content-type
        self.response.headers["Content-Type"] = Formatter.contentType(format)

        referer = ""
        if "HTTP_REFERER" in os.environ:
            referer = os.environ["HTTP_REFERER"]

        returnData = APIContent.getHackerNewsSubmittedContent(
            user, format, self.request.url, referer, self.request.remote_addr
        )

        # track this request
        GAHelper.trackGARequests("/submitted/%s" % (user), self.request.remote_addr, referer)

        if not returnData:
            returnData = ""

        # output to the browser
        self.response.out.write(Formatter.dataWrapper(format, returnData, self.request.get("callback")))
开发者ID:abuggia,项目名称:Hacker-News-Droid-API,代码行数:20,代码来源:GetHNSubmittedHandler.py

示例14: get

    def get(self, format="json", page=""):
        # set content-type
        self.response.headers["Content-Type"] = Formatter.contentType(format)

        referer = ""
        if "HTTP_REFERER" in os.environ:
            referer = os.environ["HTTP_REFERER"]

        returnData = APIContent.getHackerNewsBestContent(
            page, format, self.request.url, referer, self.request.remote_addr
        )
        if not returnData or returnData == None or returnData == "" or returnData == "None":
            # call the service again this time without the pageID
            returnData = APIContent.getHackerNewsBestContent(
                "", format, self.request.url, referer, self.request.remote_addr
            )

            # track this request
        GAHelper.trackGARequests("/best", self.request.remote_addr, referer)

        # output to the browser
        self.response.out.write(Formatter.dataWrapper(format, returnData))
开发者ID:jackfranklin,项目名称:Hacker-News-Droid-API,代码行数:22,代码来源:GetHNBestHandler.py

示例15: man

    def man(self, pattern):
        """Call viewer.sh to view man page"""
        try:
            os.makedirs(Environ.man_dir)
        except: pass

        avail = os.listdir(Environ.man_dir)

        if not os.path.exists(Environ.index_db):
            raise RuntimeError("can't find index.db")

        conn = sqlite3.connect(Environ.index_db)
        cursor = conn.cursor()

        # Try direct match
        try:
            page_name, url = cursor.execute('SELECT name,url FROM CPPMAN WHERE'
                    ' name="%s" ORDER BY LENGTH(name)' % pattern).fetchone()
        except TypeError:
            # Try standard library
            try:
                page_name, url = cursor.execute('SELECT name,url FROM CPPMAN'
                        ' WHERE name="std::%s" ORDER BY LENGTH(name)'
                        % pattern).fetchone()
            except TypeError:
                try:
                    page_name, url = cursor.execute('SELECT name,url FROM '
                        'CPPMAN WHERE name LIKE "%%%s%%" ORDER BY LENGTH(name)'
                        % pattern).fetchone()
                except TypeError:
                    raise RuntimeError('No manual entry for ' + pattern)

        finally:
            conn.close()

        page_name = page_name.replace('/', '_')
        #if page_name + '.3.gz' not in avail or self.forced:
            #self.cache_man_page(url, page_name)
            #self.update_mandb()

        pager = Environ.pager if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() else Environ.renderer

        # Call viewer
        #pid = os.fork()
        #if pid == 0:
            #out = os.execl('/bin/sh', '/bin/sh', pager,
                           #page_name + '.3.gz',
                           #str(Formatter.get_width()), Environ.pager_config,
                           #page_name)
        p = subprocess.Popen([pager, page_name + '.3.gz', str(Formatter.get_width()), Environ.pager_config, page_name], stdout=subprocess.PIPE)
        return {'page':page_name, 'out':p.stdout.read()}
开发者ID:zhenbinwu,项目名称:benwu,代码行数:51,代码来源:cppman.py


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