summaryrefslogtreecommitdiff
path: root/corpus/xml-tok.py
blob: 4357ced63adb09f07b972d16ef432c40f2e5ab24 (plain)
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
#!/usr/bin/env python

import os
import re
import subprocess
import sys

# Tokenize XML files with tokenize-anything.sh
# in:  <seg id="963"> The earnings on its 10-year bonds are 28.45%. </seg>
# out: <seg id="963"> The earnings on its 10 - year bonds are 28.45 % . </seg>

def escape(s):
    return s.replace('&', '&amp;').replace('>', '&gt;').replace('<', '&lt;').replace('"', '&quot;').replace('\'', '&apos;')

def unescape(s):
    return s.replace('&gt;', '>').replace('&lt;', '<').replace('&quot;', '"').replace('&apos;', '\'').replace('&amp;', '&')

def main():
    tok = subprocess.Popen([os.path.join(os.path.dirname(__file__), 'tokenize-anything.sh'), '-u'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        line = line.strip()
        pieces = []
        eol = len(line)
        pos = 0
        while pos < eol:
            next = line.find('<', pos)
            if next == -1:
                next = eol
            tok.stdin.write('{}\n'.format(unescape(line[pos:next])))
            pieces.append(escape(tok.stdout.readline().strip()))
            if next == eol:
                break
            pos = line.find('>', next + 1)
            if pos == -1:
                pos = eol
            else:
                pos += 1
            pieces.append(line[next:pos])
        sys.stdout.write('{}\n'.format(' '.join(pieces).strip()))
    tok.stdin.close()
    tok.wait()

if __name__ == '__main__':
    main()