Extract and Parse ODF Files with Python
Listing 2. List the Files in the ODT Archive
import sys, zipfile myfile = zipfile.ZipFile(sys.argv) listoffiles = myfile.infolist() for s in listoffiles: print s.orig_filename
The import statement allows you to use the sys module for getting a command-line argument of the file, and the zipfile module loads in the functionality for reading and unzipping files. As you saw from the Python shell, the infolist() method on the zipfile archive lists the files in it. So iterating over the items from the infolist() and then calling an orig_filename member function gives you a list of all files in the archive.
For more detailed information, try something like this:
print s.orig_filename, s.date_time, s.filename, ↪s.file_size, s.compress_size
You will receive more information about the file, quite similar to this:
mimetype (2006, 9, 9, 7, 50, 10) mimetype 39 39 Configurations2/statusbar/ (2006, 9, 9, 7, 50, 10) Configurations2/statusbar/ 0 0 Configurations2/accelerator/current.xml ↪(2006, 9, 9, 7, 50, 10) Configurations2/accelerator/current.xml 0 2 Configurations2/floater/ (2006, 9, 9, 7, 50, 10) Configurations2/floater/ 0 0 ...SNIPPED FOR BREVITY...
A typical ODF text file (with the .odt extension) will have some of the following files when unzipped. Here's the output:
mimetype Configurations2/statusbar/ Configurations2/accelerator/current.xml Configurations2/floater/ Configurations2/popupmenu/ Configurations2/progressbar/ Configurations2/menubar/ Configurations2/toolbar/ Configurations2/images/Bitmaps/ layout-cache content.xml styles.xml meta.xml Thumbnails/thumbnail.png settings.xml META-INF/manifest.xml
The most important file in the archive is the content.xml file, because it contains the data for the document itself. I discuss this file here; however, for detailed information on each tag and so on, take a look at the specification in the 2,000+-page PDF file from the OASIS Web site (see Resources).
Basically, the content.xml file looks like a DHTML file with tags for all the contents. The tag I was concerned with most for my search operation was the <text:p> tag and its closing tag </text:p>, which wraps paragraphs in a document. I'll show you how to get this tag from a content file later in this article.
Other files of interest in the archive are the META-INF/manifest.xml, mimetype, meta.xml and styles.xml. Other files simply contain data for configurations for the word processors reading and displaying the contents file.
The manifest is simply an XML file with a listing of all the files in the zipped archive. The mimetype file is a single line containing the mimetype of the content file. The meta.xml contains information about the author, creation date and so on. The styles file contains all the formatting styles for displaying the file.
You can extract any of these files from the ODF file with the read() method on the zip object to get it as a very long string. Once read, you can modify, view and write the whole string to disk as an independent file. Listing 3 shows how to extract the manifest.xml file.
Listing 3. Extracting Files for the ODT Archive
import sys, zipfile if len(sys.argv) < 2: print "Usage: extract odf-filename outputfilename sys.exit(0) myfile = zipfile.ZipFile(sys.argv) listoffiles = myfile.infolist() for s in listoffiles: if s.orig_filename == 'META-INF/manifest.xml': fd = open(sys.argv,'w') bh = myfile.read(s.orig_filename) fd.write(bh) fd.close()
For more than one file, you can use a list instead of the if clause:
if s.orig_filename in ['content.xml', 'styles.xml']:
This way, you can extract whatever files you need to look at simply by reading in their contents and either manipulating them or writing them off to disk.
The contents of an XML file are best suited for manipulation as a tree structure. Use the XML parsing capabilities in Python to get a tree of all the nodes within an XML file. Once you have the tree in a content file, you easily can get to the <text:p> nodes. You don't really have to extract the file to disk, because you also can run an XML parser on the string just as well as reading from a file.
There are two types of XML parsers, SAX and DOM. The SAX parser is faster but less memory-intensive, because it reads and parses an input file one tag at a time. You have only one tag at a time to work with and must track data yourself. In contrast, the DOM parser reads the entire file into memory and therefore provides better options for navigating and manipulating the XML nodes.
Let's look at examples of using both SAX and DOM, so you can see which one suits your purpose. The SAX example shows how to extract unique node names from an XML file. The DOM example illustrates how to read values from within specific nodes once the file has been read completely into memory.
First, let's use the SAX parser to see what nodes are available in the content.xml file. The code simply prints the name of each type node found in the file. Note that for different types of files you may get different node names (Listing 4).
|Dynamic DNS—an Object Lesson in Problem Solving||May 21, 2013|
|Using Salt Stack and Vagrant for Drupal Development||May 20, 2013|
|Making Linux and Android Get Along (It's Not as Hard as It Sounds)||May 16, 2013|
|Drupal Is a Framework: Why Everyone Needs to Understand This||May 15, 2013|
|Home, My Backup Data Center||May 13, 2013|
|Non-Linux FOSS: Seashore||May 10, 2013|
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- RSS Feeds
- Readers' Choice Awards
- Tech Tip: Really Simple HTTP Server with Python
3 hours 3 min ago
- Reply to comment | Linux Journal
3 hours 36 min ago
- All the articles you talked
5 hours 59 min ago
- All the articles you talked
6 hours 3 min ago
- All the articles you talked
6 hours 4 min ago
10 hours 29 min ago
- Keeping track of IP address
12 hours 20 min ago
- Roll your own dynamic dns
17 hours 33 min ago
- Please correct the URL for Salt Stack's web site
20 hours 44 min ago
- Android is Linux -- why no better inter-operation
23 hours 16 sec ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi
It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?