api.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. # Natural Language Toolkit: API for Corpus Readers
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Steven Bird <stevenbird1@gmail.com>
  5. # Edward Loper <edloper@gmail.com>
  6. # URL: <http://nltk.org/>
  7. # For license information, see LICENSE.TXT
  8. """
  9. API for corpus readers.
  10. """
  11. import os
  12. import re
  13. from collections import defaultdict
  14. from itertools import chain
  15. from nltk.data import PathPointer, FileSystemPathPointer, ZipFilePathPointer
  16. from nltk.corpus.reader.util import *
  17. class CorpusReader(object):
  18. """
  19. A base class for "corpus reader" classes, each of which can be
  20. used to read a specific corpus format. Each individual corpus
  21. reader instance is used to read a specific corpus, consisting of
  22. one or more files under a common root directory. Each file is
  23. identified by its ``file identifier``, which is the relative path
  24. to the file from the root directory.
  25. A separate subclass is defined for each corpus format. These
  26. subclasses define one or more methods that provide 'views' on the
  27. corpus contents, such as ``words()`` (for a list of words) and
  28. ``parsed_sents()`` (for a list of parsed sentences). Called with
  29. no arguments, these methods will return the contents of the entire
  30. corpus. For most corpora, these methods define one or more
  31. selection arguments, such as ``fileids`` or ``categories``, which can
  32. be used to select which portion of the corpus should be returned.
  33. """
  34. def __init__(self, root, fileids, encoding="utf8", tagset=None):
  35. """
  36. :type root: PathPointer or str
  37. :param root: A path pointer identifying the root directory for
  38. this corpus. If a string is specified, then it will be
  39. converted to a ``PathPointer`` automatically.
  40. :param fileids: A list of the files that make up this corpus.
  41. This list can either be specified explicitly, as a list of
  42. strings; or implicitly, as a regular expression over file
  43. paths. The absolute path for each file will be constructed
  44. by joining the reader's root to each file name.
  45. :param encoding: The default unicode encoding for the files
  46. that make up the corpus. The value of ``encoding`` can be any
  47. of the following:
  48. - A string: ``encoding`` is the encoding name for all files.
  49. - A dictionary: ``encoding[file_id]`` is the encoding
  50. name for the file whose identifier is ``file_id``. If
  51. ``file_id`` is not in ``encoding``, then the file
  52. contents will be processed using non-unicode byte strings.
  53. - A list: ``encoding`` should be a list of ``(regexp, encoding)``
  54. tuples. The encoding for a file whose identifier is ``file_id``
  55. will be the ``encoding`` value for the first tuple whose
  56. ``regexp`` matches the ``file_id``. If no tuple's ``regexp``
  57. matches the ``file_id``, the file contents will be processed
  58. using non-unicode byte strings.
  59. - None: the file contents of all files will be
  60. processed using non-unicode byte strings.
  61. :param tagset: The name of the tagset used by this corpus, to be used
  62. for normalizing or converting the POS tags returned by the
  63. tagged_...() methods.
  64. """
  65. # Convert the root to a path pointer, if necessary.
  66. if isinstance(root, str) and not isinstance(root, PathPointer):
  67. m = re.match("(.*\.zip)/?(.*)$|", root)
  68. zipfile, zipentry = m.groups()
  69. if zipfile:
  70. root = ZipFilePathPointer(zipfile, zipentry)
  71. else:
  72. root = FileSystemPathPointer(root)
  73. elif not isinstance(root, PathPointer):
  74. raise TypeError("CorpusReader: expected a string or a PathPointer")
  75. # If `fileids` is a regexp, then expand it.
  76. if isinstance(fileids, str):
  77. fileids = find_corpus_fileids(root, fileids)
  78. self._fileids = fileids
  79. """A list of the relative paths for the fileids that make up
  80. this corpus."""
  81. self._root = root
  82. """The root directory for this corpus."""
  83. # If encoding was specified as a list of regexps, then convert
  84. # it to a dictionary.
  85. if isinstance(encoding, list):
  86. encoding_dict = {}
  87. for fileid in self._fileids:
  88. for x in encoding:
  89. (regexp, enc) = x
  90. if re.match(regexp, fileid):
  91. encoding_dict[fileid] = enc
  92. break
  93. encoding = encoding_dict
  94. self._encoding = encoding
  95. """The default unicode encoding for the fileids that make up
  96. this corpus. If ``encoding`` is None, then the file
  97. contents are processed using byte strings."""
  98. self._tagset = tagset
  99. def __repr__(self):
  100. if isinstance(self._root, ZipFilePathPointer):
  101. path = "%s/%s" % (self._root.zipfile.filename, self._root.entry)
  102. else:
  103. path = "%s" % self._root.path
  104. return "<%s in %r>" % (self.__class__.__name__, path)
  105. def ensure_loaded(self):
  106. """
  107. Load this corpus (if it has not already been loaded). This is
  108. used by LazyCorpusLoader as a simple method that can be used to
  109. make sure a corpus is loaded -- e.g., in case a user wants to
  110. do help(some_corpus).
  111. """
  112. pass # no need to actually do anything.
  113. def readme(self):
  114. """
  115. Return the contents of the corpus README file, if it exists.
  116. """
  117. return self.open("README").read()
  118. def license(self):
  119. """
  120. Return the contents of the corpus LICENSE file, if it exists.
  121. """
  122. return self.open("LICENSE").read()
  123. def citation(self):
  124. """
  125. Return the contents of the corpus citation.bib file, if it exists.
  126. """
  127. return self.open("citation.bib").read()
  128. def fileids(self):
  129. """
  130. Return a list of file identifiers for the fileids that make up
  131. this corpus.
  132. """
  133. return self._fileids
  134. def abspath(self, fileid):
  135. """
  136. Return the absolute path for the given file.
  137. :type fileid: str
  138. :param fileid: The file identifier for the file whose path
  139. should be returned.
  140. :rtype: PathPointer
  141. """
  142. return self._root.join(fileid)
  143. def abspaths(self, fileids=None, include_encoding=False, include_fileid=False):
  144. """
  145. Return a list of the absolute paths for all fileids in this corpus;
  146. or for the given list of fileids, if specified.
  147. :type fileids: None or str or list
  148. :param fileids: Specifies the set of fileids for which paths should
  149. be returned. Can be None, for all fileids; a list of
  150. file identifiers, for a specified set of fileids; or a single
  151. file identifier, for a single file. Note that the return
  152. value is always a list of paths, even if ``fileids`` is a
  153. single file identifier.
  154. :param include_encoding: If true, then return a list of
  155. ``(path_pointer, encoding)`` tuples.
  156. :rtype: list(PathPointer)
  157. """
  158. if fileids is None:
  159. fileids = self._fileids
  160. elif isinstance(fileids, str):
  161. fileids = [fileids]
  162. paths = [self._root.join(f) for f in fileids]
  163. if include_encoding and include_fileid:
  164. return list(zip(paths, [self.encoding(f) for f in fileids], fileids))
  165. elif include_fileid:
  166. return list(zip(paths, fileids))
  167. elif include_encoding:
  168. return list(zip(paths, [self.encoding(f) for f in fileids]))
  169. else:
  170. return paths
  171. def open(self, file):
  172. """
  173. Return an open stream that can be used to read the given file.
  174. If the file's encoding is not None, then the stream will
  175. automatically decode the file's contents into unicode.
  176. :param file: The file identifier of the file to read.
  177. """
  178. encoding = self.encoding(file)
  179. stream = self._root.join(file).open(encoding)
  180. return stream
  181. def encoding(self, file):
  182. """
  183. Return the unicode encoding for the given corpus file, if known.
  184. If the encoding is unknown, or if the given file should be
  185. processed using byte strings (str), then return None.
  186. """
  187. if isinstance(self._encoding, dict):
  188. return self._encoding.get(file)
  189. else:
  190. return self._encoding
  191. def _get_root(self):
  192. return self._root
  193. root = property(
  194. _get_root,
  195. doc="""
  196. The directory where this corpus is stored.
  197. :type: PathPointer""",
  198. )
  199. ######################################################################
  200. # { Corpora containing categorized items
  201. ######################################################################
  202. class CategorizedCorpusReader(object):
  203. """
  204. A mixin class used to aid in the implementation of corpus readers
  205. for categorized corpora. This class defines the method
  206. ``categories()``, which returns a list of the categories for the
  207. corpus or for a specified set of fileids; and overrides ``fileids()``
  208. to take a ``categories`` argument, restricting the set of fileids to
  209. be returned.
  210. Subclasses are expected to:
  211. - Call ``__init__()`` to set up the mapping.
  212. - Override all view methods to accept a ``categories`` parameter,
  213. which can be used *instead* of the ``fileids`` parameter, to
  214. select which fileids should be included in the returned view.
  215. """
  216. def __init__(self, kwargs):
  217. """
  218. Initialize this mapping based on keyword arguments, as
  219. follows:
  220. - cat_pattern: A regular expression pattern used to find the
  221. category for each file identifier. The pattern will be
  222. applied to each file identifier, and the first matching
  223. group will be used as the category label for that file.
  224. - cat_map: A dictionary, mapping from file identifiers to
  225. category labels.
  226. - cat_file: The name of a file that contains the mapping
  227. from file identifiers to categories. The argument
  228. ``cat_delimiter`` can be used to specify a delimiter.
  229. The corresponding argument will be deleted from ``kwargs``. If
  230. more than one argument is specified, an exception will be
  231. raised.
  232. """
  233. self._f2c = None #: file-to-category mapping
  234. self._c2f = None #: category-to-file mapping
  235. self._pattern = None #: regexp specifying the mapping
  236. self._map = None #: dict specifying the mapping
  237. self._file = None #: fileid of file containing the mapping
  238. self._delimiter = None #: delimiter for ``self._file``
  239. if "cat_pattern" in kwargs:
  240. self._pattern = kwargs["cat_pattern"]
  241. del kwargs["cat_pattern"]
  242. elif "cat_map" in kwargs:
  243. self._map = kwargs["cat_map"]
  244. del kwargs["cat_map"]
  245. elif "cat_file" in kwargs:
  246. self._file = kwargs["cat_file"]
  247. del kwargs["cat_file"]
  248. if "cat_delimiter" in kwargs:
  249. self._delimiter = kwargs["cat_delimiter"]
  250. del kwargs["cat_delimiter"]
  251. else:
  252. raise ValueError(
  253. "Expected keyword argument cat_pattern or " "cat_map or cat_file."
  254. )
  255. if "cat_pattern" in kwargs or "cat_map" in kwargs or "cat_file" in kwargs:
  256. raise ValueError(
  257. "Specify exactly one of: cat_pattern, " "cat_map, cat_file."
  258. )
  259. def _init(self):
  260. self._f2c = defaultdict(set)
  261. self._c2f = defaultdict(set)
  262. if self._pattern is not None:
  263. for file_id in self._fileids:
  264. category = re.match(self._pattern, file_id).group(1)
  265. self._add(file_id, category)
  266. elif self._map is not None:
  267. for (file_id, categories) in self._map.items():
  268. for category in categories:
  269. self._add(file_id, category)
  270. elif self._file is not None:
  271. for line in self.open(self._file).readlines():
  272. line = line.strip()
  273. file_id, categories = line.split(self._delimiter, 1)
  274. if file_id not in self.fileids():
  275. raise ValueError(
  276. "In category mapping file %s: %s "
  277. "not found" % (self._file, file_id)
  278. )
  279. for category in categories.split(self._delimiter):
  280. self._add(file_id, category)
  281. def _add(self, file_id, category):
  282. self._f2c[file_id].add(category)
  283. self._c2f[category].add(file_id)
  284. def categories(self, fileids=None):
  285. """
  286. Return a list of the categories that are defined for this corpus,
  287. or for the file(s) if it is given.
  288. """
  289. if self._f2c is None:
  290. self._init()
  291. if fileids is None:
  292. return sorted(self._c2f)
  293. if isinstance(fileids, str):
  294. fileids = [fileids]
  295. return sorted(set.union(*[self._f2c[d] for d in fileids]))
  296. def fileids(self, categories=None):
  297. """
  298. Return a list of file identifiers for the files that make up
  299. this corpus, or that make up the given category(s) if specified.
  300. """
  301. if categories is None:
  302. return super(CategorizedCorpusReader, self).fileids()
  303. elif isinstance(categories, str):
  304. if self._f2c is None:
  305. self._init()
  306. if categories in self._c2f:
  307. return sorted(self._c2f[categories])
  308. else:
  309. raise ValueError("Category %s not found" % categories)
  310. else:
  311. if self._f2c is None:
  312. self._init()
  313. return sorted(set.union(*[self._c2f[c] for c in categories]))
  314. ######################################################################
  315. # { Treebank readers
  316. ######################################################################
  317. # [xx] is it worth it to factor this out?
  318. class SyntaxCorpusReader(CorpusReader):
  319. """
  320. An abstract base class for reading corpora consisting of
  321. syntactically parsed text. Subclasses should define:
  322. - ``__init__``, which specifies the location of the corpus
  323. and a method for detecting the sentence blocks in corpus files.
  324. - ``_read_block``, which reads a block from the input stream.
  325. - ``_word``, which takes a block and returns a list of list of words.
  326. - ``_tag``, which takes a block and returns a list of list of tagged
  327. words.
  328. - ``_parse``, which takes a block and returns a list of parsed
  329. sentences.
  330. """
  331. def _parse(self, s):
  332. raise NotImplementedError()
  333. def _word(self, s):
  334. raise NotImplementedError()
  335. def _tag(self, s):
  336. raise NotImplementedError()
  337. def _read_block(self, stream):
  338. raise NotImplementedError()
  339. def raw(self, fileids=None):
  340. if fileids is None:
  341. fileids = self._fileids
  342. elif isinstance(fileids, str):
  343. fileids = [fileids]
  344. return concat([self.open(f).read() for f in fileids])
  345. def parsed_sents(self, fileids=None):
  346. reader = self._read_parsed_sent_block
  347. return concat(
  348. [
  349. StreamBackedCorpusView(fileid, reader, encoding=enc)
  350. for fileid, enc in self.abspaths(fileids, True)
  351. ]
  352. )
  353. def tagged_sents(self, fileids=None, tagset=None):
  354. def reader(stream):
  355. return self._read_tagged_sent_block(stream, tagset)
  356. return concat(
  357. [
  358. StreamBackedCorpusView(fileid, reader, encoding=enc)
  359. for fileid, enc in self.abspaths(fileids, True)
  360. ]
  361. )
  362. def sents(self, fileids=None):
  363. reader = self._read_sent_block
  364. return concat(
  365. [
  366. StreamBackedCorpusView(fileid, reader, encoding=enc)
  367. for fileid, enc in self.abspaths(fileids, True)
  368. ]
  369. )
  370. def tagged_words(self, fileids=None, tagset=None):
  371. def reader(stream):
  372. return self._read_tagged_word_block(stream, tagset)
  373. return concat(
  374. [
  375. StreamBackedCorpusView(fileid, reader, encoding=enc)
  376. for fileid, enc in self.abspaths(fileids, True)
  377. ]
  378. )
  379. def words(self, fileids=None):
  380. return concat(
  381. [
  382. StreamBackedCorpusView(fileid, self._read_word_block, encoding=enc)
  383. for fileid, enc in self.abspaths(fileids, True)
  384. ]
  385. )
  386. # ------------------------------------------------------------
  387. # { Block Readers
  388. def _read_word_block(self, stream):
  389. return list(chain(*self._read_sent_block(stream)))
  390. def _read_tagged_word_block(self, stream, tagset=None):
  391. return list(chain(*self._read_tagged_sent_block(stream, tagset)))
  392. def _read_sent_block(self, stream):
  393. return list(filter(None, [self._word(t) for t in self._read_block(stream)]))
  394. def _read_tagged_sent_block(self, stream, tagset=None):
  395. return list(
  396. filter(None, [self._tag(t, tagset) for t in self._read_block(stream)])
  397. )
  398. def _read_parsed_sent_block(self, stream):
  399. return list(filter(None, [self._parse(t) for t in self._read_block(stream)]))
  400. # } End of Block Readers
  401. # ------------------------------------------------------------