當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。