Python's processing of XML and write operations for files 1__python

Source: Internet
Author: User

Today I looked up some python processing of XML documents, before using Java to process XML files, this should be used later, here first record the most basic use of the operation.

The XML document format to parse is


You can do some processing with Notepad first.

The code is:

Try:
    import xml.etree.cElementTree as et
except importerror:
    import xml.etree.ElementTree as et tree

= Et.parse (' Test_new1.xml ')
root = Tree.getroot ()
i = 0 for child in
Root[0:10]:
    title = Child.findall (' News_title ') Context
    = Child.findall (' news_body ')
    #这里是测试, a total of 10,000 articles, so named
    filename = '%05d.txt '%i
    #title是个列表, with text can get content
    t = title[0].text + ' + context[ 0].text.replace ("\ T", ""). Replace ("\ n", "")
    t = T.encode ("Utf-8") with
    open (filename, "w") as F:
        F.write (t)
    i + + 1 
    #print title[0].text + ' + context[0].text

In fact, is also on the Internet to see other people write things, to imitate, changed to apply their own code.

The Try statement is the introduction of the packet processing XML, as far as possible in the C language compiled import xml.etree.cElementTree as ET to faster, and less memory consumption

and import xml.etree.cElementTree as ET is not very safe.

One thing to be aware of is that Python writes data to encode the data in the form of ' utf-8 ' when it processes Chinese documents.

Then you can do some participle, text classification and other tasks.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.