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

Python sax.parseString函数代码示例

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

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



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

示例1: process

  def process(self, wealth, imported_file, account=None):
    gzip_file = GzipFile(fileobj=imported_file.file)
    decompressed = gzip_file.read()
    parser = make_parser()
    model = {
        'accounts': {},
        'categories': {},
        'currency': [],
        'transactions': [],
        'category_splits': [],
        'account_splits': [],
        'wealth': wealth }
    handler = KMYXmlHandler(model)
    parser.setContentHandler(handler)
    parseString(decompressed, handler)

    accounts = model['accounts']
    categories = self.__build_category_tree(model['categories'])
    transactions = model['transactions']
    account_splits = model['account_splits']
    category_splits = model['category_splits']

    # if main currencies differ, re-calculate
    if model['currency'] != model['wealth'].currency:
      exchange_rate = get_rate(model['currency'], model['wealth'].currency)
      for split in category_splits:
        split.amount *= exchange_rate

    self.accounts = accounts.values()
    self.categories = categories.values()
    self.transactions = [transaction for transaction in transactions if transaction.date]
    self.category_splits = [split for split in category_splits if split.category ]
    self.account_splits = [split for split in account_splits if split.account ]
    self.currency = model['currency']
开发者ID:drseergio,项目名称:fruitcoins,代码行数:34,代码来源:kmy_importer.py


示例2: checkStatus

def checkStatus(seHost):

    # Check if the node is in status downtime
    cmdString = CURL_CMD + "\"" + GOCDB_DOWNTIME_URL + seHost + "\""
    if DEBUG: print "Command: " + cmdString
    status, output = commands.getstatusoutput(cmdString)
    if DEBUG: print "Response: " + output
    if status <> 0:
        print "Error when querying the GOCDB for downtimes: " + output
    else:
        parseString(output, SaxDowntimeHandle())
    
    # Check if the node is in status "not in production" or "not monitored"
    cmdString = CURL_CMD + "\"" + GOCDB_SERVICE_URL + seHost + "\""
    if DEBUG: print "Command: " + cmdString
    status, output = commands.getstatusoutput(cmdString)
    if DEBUG: print "Response: " + output
    if status <> 0:
        print "Error when querying the GOCDB for service status: " + output
    else:
        parseString(output, SaxServiceHandle())

    # Display the node status
    if len(serviceStatus) <> 0:
        if PRETTY: sys.stdout.write("  %-8s%-48s" % (service, seHost))
        else: sys.stdout.write(service + "|" + seHost + "|")
        isFirst = True
        for status in serviceStatus:
            if isFirst: sys.stdout.write(status)
            else: sys.stdout.write(", " + status)
            isFirst = False
        print
开发者ID:frmichel,项目名称:vo-support-tools,代码行数:32,代码来源:gocdb-service-status.py


示例3: __init__

    def __init__(self, msw):
        """
        A list of objects in the iServer database.

        The msw argument can either be a string containing the XML
        contents of the database or a session object.  If a session is
        passed, it will be used to get the database.

        Each type is a callable object (for use in XML parser
        dispatching) and has an associated long name and a more
        convenient short name for use in test scripts.  Beware of the
        short names when using 'from iserver import *' - they are
        common and could collide with test script objects.  First
        character is capitalized.
        """
        if type(msw) is ListType:
            # A text stream created by file.readlines()
            self.rawXml = string.join(msw)
        else:
            self.msw = msw
            self._getDatabaseFromMSW()
        parser = sax.make_parser()
        handler = IServerHandler()
        sax.parseString(self.rawXml, handler)
        for i in handler.objList:
            self.append(i)
开发者ID:AkankshaGovil,项目名称:Automation,代码行数:26,代码来源:iserver.py


示例4: fetch_index

def fetch_index():
    """Return an iterable of every project name on PyPI."""

    r = requests.get('https://pypi.python.org/simple/')
    sax_handler = PyPIIndexHandler()
    sax.parseString(r.text, sax_handler)
    return sax_handler.projects
开发者ID:cfirmo33,项目名称:depsy,代码行数:7,代码来源:get_pypi_packages_metadata.py


示例5: test_case1

    def test_case1(self):
        str1= bytes(
            '<?xml version="1.0" encoding="utf-8" standalone="no" ?>\n'
            '<root>\r\n'
            '  <value1>5</value1>\r\n'
            '  <value2>1.23</value2>\n'
            '  <section first="1" second="long string">\n'
            '    <value3>on</value3>\n'
            '    <value4>1</value4>\n'
            '    <value4>2</value4>\n'
            '    <value4>42</value4>\n'
            '  </section>\n'
            '</root>'.encode("utf-8") )

        result= str(
            '<?xml version="1.0" encoding="utf-8"?>\n'
            '<root>\n'
            '  <value1>5</value1>\n'
            '  <value2>1.23</value2>\n'
            '  <section first="1" second="long string">\n'
            '    <value3>on</value3>\n'
            '    <value4>1</value4>\n'
            '    <value4>2</value4>\n'
            '    <value4>42</value4>\n'
            '  </section>\n'
            '</root>\n' )

        parseString(str1, XmlReader(self.handler1))
        #print( self.stdout.getvalue() )
        self.assertEqual(result, self.stdout.getvalue() )
开发者ID:claashk,项目名称:python-config,代码行数:30,代码来源:xml_writer.py


示例6: read_applexml_string

def read_applexml_string(data, sql_filename):
    '''Parses the data as Apple XML format. Returns the top node.'''
    #parser = sax.make_parser()
    handler = AppleXMLHandler()
    #parser.setContentHandler(handler)
    #parser.setEntityResolver(AppleXMLResolver())
    sax.parseString(data, handler)
    album_xml = handler.gettopnode()
    
    if sql_filename:
        # keywords are no longer available in XML
        # quick hack to pull them out of the sqlite database instead
        conn = sqlite3.connect(sql_filename)
        c = conn.cursor()
        photos = album_xml['Master Image List']
        for key in photos:
            photo = photos[key]
        
            if 'Keywords' not in photo:
                photo['Keywords'] = []
        
            c.execute('select keywordId from RKKeywordForVersion where versionId is ?', (key,))
            for keyword in c.fetchall():
                if keyword:
                    photo['Keywords'].append(keyword[0])
    
        album_xml['List of Keywords'] = {}
        c.execute('select modelId, name from RKKeyword')
        for keyword in c.fetchall():
            album_xml['List of Keywords'][keyword[0]] = keyword[1]
    
    return album_xml
开发者ID:alex-ios,项目名称:phoshare,代码行数:32,代码来源:applexml.py


示例7: __init__

 def __init__(self, uri):
     self.uri = uri
     self.xml = download_http_content(uri)
     self.handler = None
     self._capabilities = [] 
     self.uriHandler = UriGadgetHandler ()
     parseString(self.xml, self.uriHandler)
开发者ID:conwetlab,项目名称:ezwebplatform,代码行数:7,代码来源:templateParser.py


示例8: check

    def check(self, dialog_on_none=False):
        """
        This function should be called whenever a version test is desired
        (eg. in the mainloop on a timer).  If a dialog is requested, set
        dialog_on_none.
        """
        data = self.__get_update_file()
        if data:
            print data
            sax.parseString(data, self)

            for type in ["major", "minor"]:
                available, version = self.__new_version_available[type]
                if available:
                    if self.__remind_again[type]:
                        dialog.info(_("A version update is available"),
                                    _("You are running version %(version)s.\n\n"
                                      "Version %(newer_version)s is available "
                                      "at %(URL)s.") %
                                        {"version": VERSION,
                                         "newer_version": self.__format_version(version),
                                         "URL": dialog.urlwrap("http://www.gdesklets.de")},
                                    (_("_Stop reminding me"), lambda t=type: self.__remind(t, False)),
                                    (_("_Remind me again"), None))
                elif dialog_on_none:
                    dialog.info(_("No version updates available"),
                                _("You are running the latest version (%(version)s).") %
                                  {"version": VERSION})
                    break

        # Run again next timer expiration
        return True
开发者ID:RaumZeit,项目名称:gdesklets-core,代码行数:32,代码来源:UpdateChecker.py


示例9: xml2yaml

def xml2yaml(fname):
    handler = XMLNodeHandler()
    parseString(caffeine_cml,handler)
    PrintVisitor(handler.getroot())
    #YAMLPrintVisitor(handler.getroot())
    #print PythonObjectVisitor(handler.getroot())
    return
开发者ID:rpmuller,项目名称:pistol,代码行数:7,代码来源:yaml_utils.py


示例10: get_ping_urls

def get_ping_urls(url):
    """
    returns a two-tuple of lists, ([pingback urls],[trackback urls])
    """
    ping_urls = []
    tb_urls = []
    
    txt = urllib.urlopen(url).read()
    print "Got %d bytes" % len(txt)
    soup = bs(txt)
    # walk through the links, looking for ping-entries
    
    for a in soup.findAll('link'):
        print a
        rel = a.get('rel')
        if rel == 'pingback':
            print "Got pingback URL:", a.href
            ping_urls.append(a.get('href'))
    
    # now do t he trackbacks...
    tb_re=re.compile('(<rdf:RDF .*?</rdf:RDF>)')
    rdfdata = RDF()
    for x in tb_re.findall(txt.replace('\n',' ')):
        parseString(x, rdfdata)
        # print rdf.ids
        print "URL:", rdfdata.attrs.get('dc:identifier')
        print "Trackback URL:", rdfdata.attrs.get('trackback:ping')
        tb_urls.append(rdfdata.attrs.get('trackback:ping'))
    
    return ping_urls, tb_urls
开发者ID:rubeon,项目名称:django-xblog,代码行数:30,代码来源:trackbacktest.py


示例11: test_case1

    def test_case1(self):
        str1= bytes(
            '<?xml version="1.0" encoding="UTF-8" standalone="no" ?>\n'
            '<root>\r\n'
            '  <value1>5</value1>\r\n'
            '  <value2>1.23</value2>\n'
            '  <section>\n'
            '    <value3>on</value3>\n'
            '    <value4>1</value4>\n'
            '    <value4>2</value4>\n'
            '    <value4>42</value4>\n'
            '  </section>\n'
            '</root>'.encode("utf-8") )

        parseString(str1, XmlReader(self.handler1))
#        except Exception as ex:
#            print("In Line {0}:{1}:\n{2}".format(handler._parent.locator.getLineNumber(),
#                                                 handler._parent.locator.getColumnNumber(),
#                                                 ex))
        self.assertEqual(self.val1, 5)
        self.assertEqual(self.val2, 1.23)
        self.assertEqual(self.val3, True)
        self.assertEqual(self.val4, [1,2,42])
        self.assertEqual(self.stderr.getvalue(), "")
        self.assertEqual(self.stdout.getvalue(), "")
开发者ID:claashk,项目名称:python-config,代码行数:25,代码来源:xml_reader.py


示例12: test_process_guid_feed

	def test_process_guid_feed(self):
		p = FakeItemProcessor();
		handler = RssHandler(p)
		parseString(guid_rss, handler)
		self.assertEqual(2, p.process_calls)
		self.assertEqual(p.last_guid, 'http://example/b')
		self.assertEqual(p.last_url, 'http://example/?page=download&tid=413995')
开发者ID:riotopsys,项目名称:rss-fetch,代码行数:7,代码来源:test_rsshandler.py


示例13: do_build

 def do_build(self, source, fromFile, catalog=None, bagcls=Bag, empty=None, testmode=False):
     """TODO
     
     :param source: TODO
     :param fromFile: TODO
     :param catalog: TODO
     :param bagcls: TODO
     :param empty: TODO
     :param testmode: TODO"""
     if not testmode:
         bagImport = _SaxImporter()
     else:
         bagImport = sax.handler.ContentHandler()
     if not catalog:
         catalog = gnrclasses.GnrClassCatalog()
     bagImport.catalog = catalog
     bagImport.bagcls = bagcls
     bagImport.empty = empty
     bagImportError = _SaxImporterError()
     if fromFile:
         infile =  open(source)
         source = infile.read()
         infile.close()
             
     if isinstance(source, unicode):
         if source.startswith('<?xml'):
             source = source[source.index('?>'):]
         source = "<?xml version='1.0' encoding='UTF-8'?>%s" % source.encode('UTF-8')
     source = re.sub("&(?!([a-zA-Z][a-zA-Z0-9]*|#\d+);)", "&amp;", source)
     sax.parseString(source, bagImport)
     if not testmode:
         result = bagImport.bags[0][0]
         if bagImport.format == 'GenRoBag': result = result['GenRoBag']
         if result == None: result = []
         return result
开发者ID:OpenCode,项目名称:genropy,代码行数:35,代码来源:gnrbagxml.py


示例14: parseInfo

 def parseInfo(self):
     infoXml = self.checkOutput((self.svnCmd, "info", "--xml"))  # bytes in python 3.
     infoHandler = SvnInfoHandler()
     sax.parseString(infoXml, infoHandler)
     self.uuid = infoHandler.uuid
     self.url = infoHandler.url
     self.lastChangeRev = infoHandler.getLastChangeRevision()
开发者ID:markrmiller,项目名称:lucene-solr-svn2git,代码行数:7,代码来源:svnBranchToGit.py


示例15: run_instances

    def run_instances(self, image_id, instance_type_id, blocks = None, instance_count = -1, subnet_id = "", 
    private_ip_address = "", security_group_ids = None, key_name = ""):
        """
        Launch specified number of instances in your
        account.

        param args: Arguments passed to the function

        The function expects following arguments -
        1. image id
        2. instance type id
        3. subnet id (optional)
        4. security group id (optional)
        5. key name (optional, but needed to access machine)
        6. instance count (optional)
        7. private ip address (optional)
        8. block device mapping (optional)
        """
        response = instance.run_instances(self.url, self.verb, self.headers,
                                      self.version, image_id, instance_type_id, blocks, instance_count, subnet_id, private_ip_address, security_group_ids, key_name)
        if response is not None :
            res = RunInstancesResponse.RunInstancesResponse()
            print response.text
            parseString(str(response.text), res)
            return res
        else :
            return None
开发者ID:JioCloudCompute,项目名称:jcs_python_sdk,代码行数:27,代码来源:compute.py


示例16: test_parent_child_stop_point

 def test_parent_child_stop_point(self):
     xml_handler = NaptanXMLHandler(['639'], 'identifiers')
     parseString(test_stop_areas, xml_handler)
     areas = xml_handler.annotate_stop_area_ancestry(xml_handler.stop_areas)
     points, areas = xml_handler.annotate_stop_point_ancestry(xml_handler.stop_points, areas)
     self.assertEqual(points['639000022']['child_of'][0], areas['639GSHI21581']['id'])
     self.assertEqual(areas['639GSHI21581']['parent_of'][0], points['639000022']['id'])
开发者ID:ox-it,项目名称:moxie,代码行数:7,代码来源:test_places_importer_naptan.py


示例17: parseToolXML

    def parseToolXML( self, xml, encoding=None ):

        """ Pseudo API.
        """
        parser = _TypesToolParser( encoding )
        parseString( xml, parser )
        return parser._types
开发者ID:goschtl,项目名称:zope,代码行数:7,代码来源:typeinfo.py


示例18: weatherResponse

def weatherResponse(xml):
    handler = WeatherHandler()
    parseString(xml, handler)
    if handler.city == "Aachen":
        return "<weather>The weather in %s is terrible.</weather" % handler.city
    else:
        return "<error>Unknown city %s</error>" % handler.city[:500]
开发者ID:SYNchroACK,项目名称:crits_dependencies,代码行数:7,代码来源:python_external.py


示例19: get_leo_data

def get_leo_data(source):
    """Return the root node for the specificed .leo file (path or file)"""
    parser = LeoReader()
    if g.os_path_isfile(source):
        source = g.readFileIntoEncodedString(source)
    parseString(source, parser)
    return parser.root
开发者ID:SegundoBob,项目名称:leo-editor,代码行数:7,代码来源:leosax.py


示例20: process_file

def process_file (file) :
    """parcours un fichier et retourne une liste contenant :
    (niveau, balise, attribut, valeur) ou 
    (niveau, balise, None, valeur) ou 
    (niveau, None, None, valeur)"""

    if False :
        # création d'une classe qui va parcourir le fichier XML
        p = XML.make_parser ()
        x = XML_List ()
        # on affecte au parseur une instance de la classe XML_List
        p.setContentHandler (x)
        
        # on lit le fichier file ligne par ligne,
        # chaque ligne est envoyée au parser XML 
        f = open (file, "r")
        for l in f : 
            p.feed (l)
        p.close ()
        f.close ()
        return x.get_list ()
    else :
        # autre solution : on lit le fichier
        # pour n'obtenir qu'une seule chaîne de caractères
        f  = open (file, "r")
        li = f.readlines ()
        f.close ()
        s = string.join (li)
        
        # puis on utilise une fonction qui lit la chaîne complète
        x  = XML_List ()
        XML.parseString (s, x)
        return x.get_list ()     
开发者ID:sdpython,项目名称:ensae_teaching_cs,代码行数:33,代码来源:xml_example_winamp.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python sax.ContentHandler类代码示例发布时间:2022-05-26
下一篇:
Python sax.parse函数代码示例发布时间: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