-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessing_Patents(Multiple_file).py
More file actions
55 lines (45 loc) · 1.79 KB
/
processing_Patents(Multiple_file).py
File metadata and controls
55 lines (45 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# So, the problem is that the gigantic file is actually not a valid XML, because
# it has several root elements, and XML declarations.
# It is, a matter of fact, a collection of a lot of concatenated XML documents.
# So, one solution would be to split the file into separate documents,
# so that you can process the resulting files as valid XML documents.
import xml.etree.ElementTree as ET
PATENTS = 'patent.data'
def get_root(fname):
tree = ET.parse(fname)
return tree.getroot()
def split_file(filename):
"""
Split the input file into separate files, each containing a single patent.
As a hint - each patent declaration starts with the same line that was
causing the error found in the previous exercises.
The new files should be saved w ith filename in the following format:
"{}-{}".format(filename, n) where n is a counter, starting from 0.
"""
n = -1
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
if line == '<?xml version="1.0" encoding="UTF-8"?>\n':
n += 1
g = open("{}-{}".format(filename, str(n)), 'a+')
g.write(line)
g.close()
else:
g = open("{}-{}".format(filename, str(n)), 'a+')
g.write(line)
g.close()
def test():
split_file(PATENTS)
for n in range(4):
try:
fname = "{}-{}".format(PATENTS, n)
f = open(fname, "r")
if not f.readline().startswith("<?xml"):
print ("You have not split the file {} in the correct boundary!").format(fname)
f.close()
except:
print ("Could not find file {}. Check if the filename is correct!").format(fname)
test()