PageRenderTime 51ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/nltk/nltk/toolbox/toolbox.py

http://nltk.googlecode.com/
Python | 495 lines | 453 code | 6 blank | 36 comment | 5 complexity | 39cec899b8840112633ef0abb8872804 MD5 | raw file
Possible License(s): Apache-2.0, AGPL-1.0
  1. # Natural Language Toolkit: Toolbox Reader
  2. #
  3. # Copyright (C) 2001-2011 NLTK Project
  4. # Author: Greg Aumann <greg_aumann@sil.org>
  5. # URL: <http://nltk.org>
  6. # For license information, see LICENSE.TXT
  7. """
  8. Module for reading, writing and manipulating
  9. Toolbox databases and settings files.
  10. """
  11. import os, re, codecs
  12. from StringIO import StringIO
  13. from nltk.etree.ElementTree import TreeBuilder, Element, SubElement
  14. from nltk.data import PathPointer, ZipFilePathPointer
  15. import nltk
  16. class StandardFormat(object):
  17. """
  18. Class for reading and processing standard format marker files and strings.
  19. """
  20. def __init__(self, filename=None, encoding=None):
  21. self._encoding = encoding
  22. if filename is not None:
  23. self.open(filename)
  24. def open(self, sfm_file):
  25. """Open a standard format marker file for sequential reading.
  26. @param sfm_file: name of the standard format marker input file
  27. @type sfm_file: C{string}
  28. """
  29. if isinstance(sfm_file, PathPointer):
  30. # [xx] We don't use 'rU' mode here -- do we need to?
  31. # (PathPointer.open doesn't take a mode option)
  32. self._file = sfm_file.open(self._encoding)
  33. else:
  34. self._file = codecs.open(sfm_file, 'rU', self._encoding)
  35. def open_string(self, s):
  36. """Open a standard format marker string for sequential reading.
  37. @param s: string to parse as a standard format marker input file
  38. @type s: C{string}
  39. """
  40. self._file = StringIO(s)
  41. def raw_fields(self):
  42. """Return an iterator for the fields in the standard format marker
  43. file.
  44. @return: an iterator that returns the next field in a (marker, value)
  45. tuple. Linebreaks and trailing white space are preserved except
  46. for the final newline in each field.
  47. @rtype: iterator over C{(marker, value)} tuples
  48. """
  49. join_string = '\n'
  50. line_regexp = r'^%s(?:\\(\S+)\s*)?(.*)$'
  51. # discard a BOM in the first line
  52. first_line_pat = re.compile(line_regexp % u'(?:\ufeff)?'.encode('utf8'))
  53. line_pat = re.compile(line_regexp % '')
  54. # need to get first line outside the loop for correct handling
  55. # of the first marker if it spans multiple lines
  56. file_iter = iter(self._file)
  57. line = file_iter.next()
  58. mobj = re.match(first_line_pat, line)
  59. mkr, line_value = mobj.groups()
  60. value_lines = [line_value,]
  61. self.line_num = 0
  62. for line in file_iter:
  63. self.line_num += 1
  64. mobj = re.match(line_pat, line)
  65. line_mkr, line_value = mobj.groups()
  66. if line_mkr:
  67. yield (mkr, join_string.join(value_lines))
  68. mkr = line_mkr
  69. value_lines = [line_value,]
  70. else:
  71. value_lines.append(line_value)
  72. self.line_num += 1
  73. yield (mkr, join_string.join(value_lines))
  74. def fields(self, strip=True, unwrap=True, encoding=None, errors='strict', unicode_fields=None):
  75. """Return an iterator for the fields in the standard format marker file.
  76. @param strip: strip trailing whitespace from the last line of each field
  77. @type strip: C{boolean}
  78. @param unwrap: Convert newlines in a field to spaces.
  79. @type unwrap: C{boolean}
  80. @param encoding: Name of an encoding to use. If it is specified then
  81. the C{fields} method returns unicode strings rather than non
  82. unicode strings.
  83. @type encoding: C{string} or C{None}
  84. @param errors: Error handling scheme for codec. Same as the C{decode}
  85. inbuilt string method.
  86. @type errors: C{string}
  87. @param unicode_fields: Set of marker names whose values are UTF-8 encoded.
  88. Ignored if encoding is None. If the whole file is UTF-8 encoded set
  89. C{encoding='utf8'} and leave C{unicode_fields} with its default
  90. value of None.
  91. @type unicode_fields: set or dictionary (actually any sequence that
  92. supports the 'in' operator).
  93. @return: an iterator that returns the next field in a C{(marker, value)}
  94. tuple. C{marker} and C{value} are unicode strings if an C{encoding} was specified in the
  95. C{fields} method. Otherwise they are nonunicode strings.
  96. @rtype: iterator over C{(marker, value)} tuples
  97. """
  98. if encoding is None and unicode_fields is not None:
  99. raise ValueError, 'unicode_fields is set but not encoding.'
  100. unwrap_pat = re.compile(r'\n+')
  101. for mkr, val in self.raw_fields():
  102. if encoding:
  103. if unicode_fields is not None and mkr in unicode_fields:
  104. val = val.decode('utf8', errors)
  105. else:
  106. val = val.decode(encoding, errors)
  107. mkr = mkr.decode(encoding, errors)
  108. if unwrap:
  109. val = unwrap_pat.sub(' ', val)
  110. if strip:
  111. val = val.rstrip()
  112. yield (mkr, val)
  113. def close(self):
  114. """Close a previously opened standard format marker file or string."""
  115. self._file.close()
  116. try:
  117. del self.line_num
  118. except AttributeError:
  119. pass
  120. class ToolboxData(StandardFormat):
  121. def parse(self, grammar=None, **kwargs):
  122. if grammar:
  123. return self._chunk_parse(grammar=grammar, **kwargs)
  124. else:
  125. return self._record_parse(**kwargs)
  126. def _record_parse(self, key=None, **kwargs):
  127. """
  128. Returns an element tree structure corresponding to a toolbox data file with
  129. all markers at the same level.
  130. Thus the following Toolbox database::
  131. \_sh v3.0 400 Rotokas Dictionary
  132. \_DateStampHasFourDigitYear
  133. \lx kaa
  134. \ps V.A
  135. \ge gag
  136. \gp nek i pas
  137. \lx kaa
  138. \ps V.B
  139. \ge strangle
  140. \gp pasim nek
  141. after parsing will end up with the same structure (ignoring the extra
  142. whitespace) as the following XML fragment after being parsed by
  143. ElementTree::
  144. <toolbox_data>
  145. <header>
  146. <_sh>v3.0 400 Rotokas Dictionary</_sh>
  147. <_DateStampHasFourDigitYear/>
  148. </header>
  149. <record>
  150. <lx>kaa</lx>
  151. <ps>V.A</ps>
  152. <ge>gag</ge>
  153. <gp>nek i pas</gp>
  154. </record>
  155. <record>
  156. <lx>kaa</lx>
  157. <ps>V.B</ps>
  158. <ge>strangle</ge>
  159. <gp>pasim nek</gp>
  160. </record>
  161. </toolbox_data>
  162. @param key: Name of key marker at the start of each record. If set to
  163. None (the default value) the first marker that doesn't begin with an
  164. underscore is assumed to be the key.
  165. @type key: C{string}
  166. @param kwargs: Keyword arguments passed to L{StandardFormat.fields()}
  167. @type kwargs: keyword arguments dictionary
  168. @rtype: C{ElementTree._ElementInterface}
  169. @return: contents of toolbox data divided into header and records
  170. """
  171. builder = TreeBuilder()
  172. builder.start('toolbox_data', {})
  173. builder.start('header', {})
  174. in_records = False
  175. for mkr, value in self.fields(**kwargs):
  176. if key is None and not in_records and mkr[0] != '_':
  177. key = mkr
  178. if mkr == key:
  179. if in_records:
  180. builder.end('record')
  181. else:
  182. builder.end('header')
  183. in_records = True
  184. builder.start('record', {})
  185. builder.start(mkr, {})
  186. builder.data(value)
  187. builder.end(mkr)
  188. if in_records:
  189. builder.end('record')
  190. else:
  191. builder.end('header')
  192. builder.end('toolbox_data')
  193. return builder.close()
  194. def _tree2etree(self, parent):
  195. from nltk.parse import Tree
  196. root = Element(parent.node)
  197. for child in parent:
  198. if isinstance(child, Tree):
  199. root.append(self._tree2etree(child))
  200. else:
  201. text, tag = child
  202. e = SubElement(root, tag)
  203. e.text = text
  204. return root
  205. def _chunk_parse(self, grammar=None, top_node='record', trace=0, **kwargs):
  206. """
  207. Returns an element tree structure corresponding to a toolbox data file
  208. parsed according to the chunk grammar.
  209. @type grammar: C{string}
  210. @param grammar: Contains the chunking rules used to parse the
  211. database. See L{chunk.RegExp} for documentation.
  212. @type top_node: C{string}
  213. @param top_node: The node value that should be used for the
  214. top node of the chunk structure.
  215. @type trace: C{int}
  216. @param trace: The level of tracing that should be used when
  217. parsing a text. C{0} will generate no tracing output;
  218. C{1} will generate normal tracing output; and C{2} or
  219. higher will generate verbose tracing output.
  220. @type kwargs: C{dictionary}
  221. @param kwargs: Keyword arguments passed to L{toolbox.StandardFormat.fields()}
  222. @rtype: C{ElementTree._ElementInterface}
  223. @return: Contents of toolbox data parsed according to the rules in grammar
  224. """
  225. from nltk import chunk
  226. from nltk.parse import Tree
  227. cp = chunk.RegexpParser(grammar, top_node=top_node, trace=trace)
  228. db = self.parse(**kwargs)
  229. tb_etree = Element('toolbox_data')
  230. header = db.find('header')
  231. tb_etree.append(header)
  232. for record in db.findall('record'):
  233. parsed = cp.parse([(elem.text, elem.tag) for elem in record])
  234. tb_etree.append(self._tree2etree(parsed))
  235. return tb_etree
  236. _is_value = re.compile(r"\S")
  237. def to_sfm_string(tree, encoding=None, errors='strict', unicode_fields=None):
  238. """Return a string with a standard format representation of the toolbox
  239. data in tree (tree can be a toolbox database or a single record).
  240. @param tree: flat representation of toolbox data (whole database or single record)
  241. @type tree: C{ElementTree._ElementInterface}
  242. @param encoding: Name of an encoding to use.
  243. @type encoding: C{string}
  244. @param errors: Error handling scheme for codec. Same as the C{encode}
  245. inbuilt string method.
  246. @type errors: C{string}
  247. @param unicode_fields:
  248. @type unicode_fields: C{dictionary} or C{set} of field names
  249. @rtype: C{string}
  250. @return: C{string} using standard format markup
  251. """
  252. if tree.tag == 'record':
  253. root = Element('toolbox_data')
  254. root.append(tree)
  255. tree = root
  256. if tree.tag != 'toolbox_data':
  257. raise ValueError, "not a toolbox_data element structure"
  258. if encoding is None and unicode_fields is not None:
  259. raise ValueError, \
  260. "if encoding is not specified then neither should unicode_fields"
  261. l = []
  262. for rec in tree:
  263. l.append('\n')
  264. for field in rec:
  265. mkr = field.tag
  266. value = field.text
  267. if encoding is not None:
  268. if unicode_fields is not None and mkr in unicode_fields:
  269. cur_encoding = 'utf8'
  270. else:
  271. cur_encoding = encoding
  272. if re.search(_is_value, value):
  273. l.append((u"\\%s %s\n" % (mkr, value)).encode(cur_encoding, errors))
  274. else:
  275. l.append((u"\\%s%s\n" % (mkr, value)).encode(cur_encoding, errors))
  276. else:
  277. if re.search(_is_value, value):
  278. l.append("\\%s %s\n" % (mkr, value))
  279. else:
  280. l.append("\\%s%s\n" % (mkr, value))
  281. return ''.join(l[1:])
  282. class ToolboxSettings(StandardFormat):
  283. """This class is the base class for settings files."""
  284. def __init__(self):
  285. super(ToolboxSettings, self).__init__()
  286. def parse(self, encoding=None, errors='strict', **kwargs):
  287. """Parses a settings file using ElementTree.
  288. @param encoding: encoding used by settings file
  289. @type encoding: C{string}
  290. @param errors: Error handling scheme for codec. Same as C{.decode} inbuilt method.
  291. @type errors: C{string}
  292. @param kwargs: Keyword arguments passed to L{StandardFormat.fields()}
  293. @type kwargs: keyword arguments dictionary
  294. @rtype: C{ElementTree._ElementInterface}
  295. @return: contents of toolbox settings file with a nested structure
  296. """
  297. builder = TreeBuilder()
  298. for mkr, value in self.fields(encoding=encoding, errors=errors, **kwargs):
  299. # Check whether the first char of the field marker
  300. # indicates a block start (+) or end (-)
  301. block=mkr[0]
  302. if block in ("+", "-"):
  303. mkr=mkr[1:]
  304. else:
  305. block=None
  306. # Build tree on the basis of block char
  307. if block == "+":
  308. builder.start(mkr, {})
  309. builder.data(value)
  310. elif block == '-':
  311. builder.end(mkr)
  312. else:
  313. builder.start(mkr, {})
  314. builder.data(value)
  315. builder.end(mkr)
  316. return builder.close()
  317. def to_settings_string(tree, encoding=None, errors='strict', unicode_fields=None):
  318. # write XML to file
  319. l = list()
  320. _to_settings_string(tree.getroot(), l, encoding=encoding, errors=errors, unicode_fields=unicode_fields)
  321. return ''.join(l)
  322. def _to_settings_string(node, l, **kwargs):
  323. # write XML to file
  324. tag = node.tag
  325. text = node.text
  326. if len(node) == 0:
  327. if text:
  328. l.append('\\%s %s\n' % (tag, text))
  329. else:
  330. l.append('\\%s\n' % tag)
  331. else:
  332. if text:
  333. l.append('\\+%s %s\n' % (tag, text))
  334. else:
  335. l.append('\\+%s\n' % tag)
  336. for n in node:
  337. _to_settings_string(n, l, **kwargs)
  338. l.append('\\-%s\n' % tag)
  339. return
  340. def remove_blanks(elem):
  341. """Remove all elements and subelements with no text and no child elements.
  342. @param elem: toolbox data in an elementtree structure
  343. @type elem: ElementTree._ElementInterface
  344. """
  345. out = list()
  346. for child in elem:
  347. remove_blanks(child)
  348. if child.text or len(child) > 0:
  349. out.append(child)
  350. elem[:] = out
  351. def add_default_fields(elem, default_fields):
  352. """Add blank elements and subelements specified in default_fields.
  353. @param elem: toolbox data in an elementtree structure
  354. @type elem: ElementTree._ElementInterface
  355. @param default_fields: fields to add to each type of element and subelement
  356. @type default_fields: dictionary of tuples
  357. """
  358. for field in default_fields.get(elem.tag, []):
  359. if elem.find(field) is None:
  360. SubElement(elem, field)
  361. for child in elem:
  362. add_default_fields(child, default_fields)
  363. def sort_fields(elem, field_orders):
  364. """Sort the elements and subelements in order specified in field_orders.
  365. @param elem: toolbox data in an elementtree structure
  366. @type elem: ElementTree._ElementInterface
  367. @param field_orders: order of fields for each type of element and subelement
  368. @type field_orders: dictionary of tuples
  369. """
  370. order_dicts = dict()
  371. for field, order in field_orders.items():
  372. order_dicts[field] = order_key = dict()
  373. for i, subfield in enumerate(order):
  374. order_key[subfield] = i
  375. _sort_fields(elem, order_dicts)
  376. def _sort_fields(elem, orders_dicts):
  377. """sort the children of elem"""
  378. try:
  379. order = orders_dicts[elem.tag]
  380. except KeyError:
  381. pass
  382. else:
  383. tmp = [((order.get(child.tag, 1e9), i), child) for i, child in enumerate(elem)]
  384. tmp.sort()
  385. elem[:] = [child for key, child in tmp]
  386. for child in elem:
  387. if len(child):
  388. _sort_fields(child, orders_dicts)
  389. def add_blank_lines(tree, blanks_before, blanks_between):
  390. """Add blank lines before all elements and subelements specified in blank_before.
  391. @param elem: toolbox data in an elementtree structure
  392. @type elem: ElementTree._ElementInterface
  393. @param blank_before: elements and subelements to add blank lines before
  394. @type blank_before: dictionary of tuples
  395. """
  396. try:
  397. before = blanks_before[tree.tag]
  398. between = blanks_between[tree.tag]
  399. except KeyError:
  400. for elem in tree:
  401. if len(elem):
  402. add_blank_lines(elem, blanks_before, blanks_between)
  403. else:
  404. last_elem = None
  405. for elem in tree:
  406. tag = elem.tag
  407. if last_elem is not None and last_elem.tag != tag:
  408. if tag in before and last_elem is not None:
  409. e = last_elem.getiterator()[-1]
  410. e.text = (e.text or "") + "\n"
  411. else:
  412. if tag in between:
  413. e = last_elem.getiterator()[-1]
  414. e.text = (e.text or "") + "\n"
  415. if len(elem):
  416. add_blank_lines(elem, blanks_before, blanks_between)
  417. last_elem = elem
  418. def demo():
  419. from itertools import islice
  420. # zip_path = nltk.data.find('corpora/toolbox.zip')
  421. # lexicon = ToolboxData(ZipFilePathPointer(zip_path, 'toolbox/rotokas.dic')).parse()
  422. file_path = nltk.data.find('corpora/toolbox/rotokas.dic')
  423. lexicon = ToolboxData(file_path).parse()
  424. print 'first field in fourth record:'
  425. print lexicon[3][0].tag
  426. print lexicon[3][0].text
  427. print '\nfields in sequential order:'
  428. for field in islice(lexicon.find('record'), 10):
  429. print field.tag, field.text
  430. print '\nlx fields:'
  431. for field in islice(lexicon.findall('record/lx'), 10):
  432. print field.text
  433. from nltk.etree.ElementTree import ElementTree
  434. settings = ToolboxSettings()
  435. file_path = nltk.data.find('corpora/toolbox/MDF/MDF_AltH.typ')
  436. settings.open(file_path)
  437. # settings.open(ZipFilePathPointer(zip_path, entry='toolbox/MDF/MDF_AltH.typ'))
  438. tree = settings.parse(unwrap=False, encoding='cp1252')
  439. print tree.find('expset/expMDF/rtfPageSetup/paperSize').text
  440. settings_tree = ElementTree(tree)
  441. print to_settings_string(settings_tree).encode('utf8')
  442. if __name__ == '__main__':
  443. demo()