ipipan.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. # Natural Language Toolkit: IPI PAN Corpus Reader
  2. #
  3. # Copyright (C) 2001-2020 NLTK Project
  4. # Author: Konrad Goluchowski <kodie@mimuw.edu.pl>
  5. # URL: <http://nltk.org/>
  6. # For license information, see LICENSE.TXT
  7. import functools
  8. from nltk.corpus.reader.util import StreamBackedCorpusView, concat
  9. from nltk.corpus.reader.api import CorpusReader
  10. def _parse_args(fun):
  11. @functools.wraps(fun)
  12. def decorator(self, fileids=None, **kwargs):
  13. kwargs.pop("tags", None)
  14. if not fileids:
  15. fileids = self.fileids()
  16. return fun(self, fileids, **kwargs)
  17. return decorator
  18. class IPIPANCorpusReader(CorpusReader):
  19. """
  20. Corpus reader designed to work with corpus created by IPI PAN.
  21. See http://korpus.pl/en/ for more details about IPI PAN corpus.
  22. The corpus includes information about text domain, channel and categories.
  23. You can access possible values using ``domains()``, ``channels()`` and
  24. ``categories()``. You can use also this metadata to filter files, e.g.:
  25. ``fileids(channel='prasa')``, ``fileids(categories='publicystyczny')``.
  26. The reader supports methods: words, sents, paras and their tagged versions.
  27. You can get part of speech instead of full tag by giving "simplify_tags=True"
  28. parameter, e.g.: ``tagged_sents(simplify_tags=True)``.
  29. Also you can get all tags disambiguated tags specifying parameter
  30. "one_tag=False", e.g.: ``tagged_paras(one_tag=False)``.
  31. You can get all tags that were assigned by a morphological analyzer specifying
  32. parameter "disamb_only=False", e.g. ``tagged_words(disamb_only=False)``.
  33. The IPIPAN Corpus contains tags indicating if there is a space between two
  34. tokens. To add special "no space" markers, you should specify parameter
  35. "append_no_space=True", e.g. ``tagged_words(append_no_space=True)``.
  36. As a result in place where there should be no space between two tokens new
  37. pair ('', 'no-space') will be inserted (for tagged data) and just '' for
  38. methods without tags.
  39. The corpus reader can also try to append spaces between words. To enable this
  40. option, specify parameter "append_space=True", e.g. ``words(append_space=True)``.
  41. As a result either ' ' or (' ', 'space') will be inserted between tokens.
  42. By default, xml entities like &quot; and &amp; are replaced by corresponding
  43. characters. You can turn off this feature, specifying parameter
  44. "replace_xmlentities=False", e.g. ``words(replace_xmlentities=False)``.
  45. """
  46. def __init__(self, root, fileids):
  47. CorpusReader.__init__(self, root, fileids, None, None)
  48. def raw(self, fileids=None):
  49. if not fileids:
  50. fileids = self.fileids()
  51. filecontents = []
  52. for fileid in self._list_morph_files(fileids):
  53. with open(fileid, "r") as infile:
  54. filecontents.append(infile.read())
  55. return "".join(filecontents)
  56. def channels(self, fileids=None):
  57. if not fileids:
  58. fileids = self.fileids()
  59. return self._parse_header(fileids, "channel")
  60. def domains(self, fileids=None):
  61. if not fileids:
  62. fileids = self.fileids()
  63. return self._parse_header(fileids, "domain")
  64. def categories(self, fileids=None):
  65. if not fileids:
  66. fileids = self.fileids()
  67. return [
  68. self._map_category(cat) for cat in self._parse_header(fileids, "keyTerm")
  69. ]
  70. def fileids(self, channels=None, domains=None, categories=None):
  71. if channels is not None and domains is not None and categories is not None:
  72. raise ValueError(
  73. "You can specify only one of channels, domains "
  74. "and categories parameter at once"
  75. )
  76. if channels is None and domains is None and categories is None:
  77. return CorpusReader.fileids(self)
  78. if isinstance(channels, str):
  79. channels = [channels]
  80. if isinstance(domains, str):
  81. domains = [domains]
  82. if isinstance(categories, str):
  83. categories = [categories]
  84. if channels:
  85. return self._list_morph_files_by("channel", channels)
  86. elif domains:
  87. return self._list_morph_files_by("domain", domains)
  88. else:
  89. return self._list_morph_files_by(
  90. "keyTerm", categories, map=self._map_category
  91. )
  92. @_parse_args
  93. def sents(self, fileids=None, **kwargs):
  94. return concat(
  95. [
  96. self._view(
  97. fileid, mode=IPIPANCorpusView.SENTS_MODE, tags=False, **kwargs
  98. )
  99. for fileid in self._list_morph_files(fileids)
  100. ]
  101. )
  102. @_parse_args
  103. def paras(self, fileids=None, **kwargs):
  104. return concat(
  105. [
  106. self._view(
  107. fileid, mode=IPIPANCorpusView.PARAS_MODE, tags=False, **kwargs
  108. )
  109. for fileid in self._list_morph_files(fileids)
  110. ]
  111. )
  112. @_parse_args
  113. def words(self, fileids=None, **kwargs):
  114. return concat(
  115. [
  116. self._view(fileid, tags=False, **kwargs)
  117. for fileid in self._list_morph_files(fileids)
  118. ]
  119. )
  120. @_parse_args
  121. def tagged_sents(self, fileids=None, **kwargs):
  122. return concat(
  123. [
  124. self._view(fileid, mode=IPIPANCorpusView.SENTS_MODE, **kwargs)
  125. for fileid in self._list_morph_files(fileids)
  126. ]
  127. )
  128. @_parse_args
  129. def tagged_paras(self, fileids=None, **kwargs):
  130. return concat(
  131. [
  132. self._view(fileid, mode=IPIPANCorpusView.PARAS_MODE, **kwargs)
  133. for fileid in self._list_morph_files(fileids)
  134. ]
  135. )
  136. @_parse_args
  137. def tagged_words(self, fileids=None, **kwargs):
  138. return concat(
  139. [self._view(fileid, **kwargs) for fileid in self._list_morph_files(fileids)]
  140. )
  141. def _list_morph_files(self, fileids):
  142. return [f for f in self.abspaths(fileids)]
  143. def _list_header_files(self, fileids):
  144. return [
  145. f.replace("morph.xml", "header.xml")
  146. for f in self._list_morph_files(fileids)
  147. ]
  148. def _parse_header(self, fileids, tag):
  149. values = set()
  150. for f in self._list_header_files(fileids):
  151. values_list = self._get_tag(f, tag)
  152. for v in values_list:
  153. values.add(v)
  154. return list(values)
  155. def _list_morph_files_by(self, tag, values, map=None):
  156. fileids = self.fileids()
  157. ret_fileids = set()
  158. for f in fileids:
  159. fp = self.abspath(f).replace("morph.xml", "header.xml")
  160. values_list = self._get_tag(fp, tag)
  161. for value in values_list:
  162. if map is not None:
  163. value = map(value)
  164. if value in values:
  165. ret_fileids.add(f)
  166. return list(ret_fileids)
  167. def _get_tag(self, f, tag):
  168. tags = []
  169. with open(f, "r") as infile:
  170. header = infile.read()
  171. tag_end = 0
  172. while True:
  173. tag_pos = header.find("<" + tag, tag_end)
  174. if tag_pos < 0:
  175. return tags
  176. tag_end = header.find("</" + tag + ">", tag_pos)
  177. tags.append(header[tag_pos + len(tag) + 2 : tag_end])
  178. def _map_category(self, cat):
  179. pos = cat.find(">")
  180. if pos == -1:
  181. return cat
  182. else:
  183. return cat[pos + 1 :]
  184. def _view(self, filename, **kwargs):
  185. tags = kwargs.pop("tags", True)
  186. mode = kwargs.pop("mode", 0)
  187. simplify_tags = kwargs.pop("simplify_tags", False)
  188. one_tag = kwargs.pop("one_tag", True)
  189. disamb_only = kwargs.pop("disamb_only", True)
  190. append_no_space = kwargs.pop("append_no_space", False)
  191. append_space = kwargs.pop("append_space", False)
  192. replace_xmlentities = kwargs.pop("replace_xmlentities", True)
  193. if len(kwargs) > 0:
  194. raise ValueError("Unexpected arguments: %s" % kwargs.keys())
  195. if not one_tag and not disamb_only:
  196. raise ValueError(
  197. "You cannot specify both one_tag=False and " "disamb_only=False"
  198. )
  199. if not tags and (simplify_tags or not one_tag or not disamb_only):
  200. raise ValueError(
  201. "You cannot specify simplify_tags, one_tag or "
  202. "disamb_only with functions other than tagged_*"
  203. )
  204. return IPIPANCorpusView(
  205. filename,
  206. tags=tags,
  207. mode=mode,
  208. simplify_tags=simplify_tags,
  209. one_tag=one_tag,
  210. disamb_only=disamb_only,
  211. append_no_space=append_no_space,
  212. append_space=append_space,
  213. replace_xmlentities=replace_xmlentities,
  214. )
  215. class IPIPANCorpusView(StreamBackedCorpusView):
  216. WORDS_MODE = 0
  217. SENTS_MODE = 1
  218. PARAS_MODE = 2
  219. def __init__(self, filename, startpos=0, **kwargs):
  220. StreamBackedCorpusView.__init__(self, filename, None, startpos, None)
  221. self.in_sentence = False
  222. self.position = 0
  223. self.show_tags = kwargs.pop("tags", True)
  224. self.disamb_only = kwargs.pop("disamb_only", True)
  225. self.mode = kwargs.pop("mode", IPIPANCorpusView.WORDS_MODE)
  226. self.simplify_tags = kwargs.pop("simplify_tags", False)
  227. self.one_tag = kwargs.pop("one_tag", True)
  228. self.append_no_space = kwargs.pop("append_no_space", False)
  229. self.append_space = kwargs.pop("append_space", False)
  230. self.replace_xmlentities = kwargs.pop("replace_xmlentities", True)
  231. def read_block(self, stream):
  232. sentence = []
  233. sentences = []
  234. space = False
  235. no_space = False
  236. tags = set()
  237. lines = self._read_data(stream)
  238. while True:
  239. # we may have only part of last line
  240. if len(lines) <= 1:
  241. self._seek(stream)
  242. lines = self._read_data(stream)
  243. if lines == [""]:
  244. assert not sentences
  245. return []
  246. line = lines.pop()
  247. self.position += len(line) + 1
  248. if line.startswith('<chunk type="s"'):
  249. self.in_sentence = True
  250. elif line.startswith('<chunk type="p"'):
  251. pass
  252. elif line.startswith("<tok"):
  253. if self.append_space and space and not no_space:
  254. self._append_space(sentence)
  255. space = True
  256. no_space = False
  257. orth = ""
  258. tags = set()
  259. elif line.startswith("</chunk"):
  260. if self.in_sentence:
  261. self.in_sentence = False
  262. self._seek(stream)
  263. if self.mode == self.SENTS_MODE:
  264. return [sentence]
  265. elif self.mode == self.WORDS_MODE:
  266. if self.append_space:
  267. self._append_space(sentence)
  268. return sentence
  269. else:
  270. sentences.append(sentence)
  271. elif self.mode == self.PARAS_MODE:
  272. self._seek(stream)
  273. return [sentences]
  274. elif line.startswith("<orth"):
  275. orth = line[6:-7]
  276. if self.replace_xmlentities:
  277. orth = orth.replace("&quot;", '"').replace("&amp;", "&")
  278. elif line.startswith("<lex"):
  279. if not self.disamb_only or line.find("disamb=") != -1:
  280. tag = line[line.index("<ctag") + 6 : line.index("</ctag")]
  281. tags.add(tag)
  282. elif line.startswith("</tok"):
  283. if self.show_tags:
  284. if self.simplify_tags:
  285. tags = [t.split(":")[0] for t in tags]
  286. if not self.one_tag or not self.disamb_only:
  287. sentence.append((orth, tuple(tags)))
  288. else:
  289. sentence.append((orth, tags.pop()))
  290. else:
  291. sentence.append(orth)
  292. elif line.startswith("<ns/>"):
  293. if self.append_space:
  294. no_space = True
  295. if self.append_no_space:
  296. if self.show_tags:
  297. sentence.append(("", "no-space"))
  298. else:
  299. sentence.append("")
  300. elif line.startswith("</cesAna"):
  301. pass
  302. def _read_data(self, stream):
  303. self.position = stream.tell()
  304. buff = stream.read(4096)
  305. lines = buff.split("\n")
  306. lines.reverse()
  307. return lines
  308. def _seek(self, stream):
  309. stream.seek(self.position)
  310. def _append_space(self, sentence):
  311. if self.show_tags:
  312. sentence.append((" ", "space"))
  313. else:
  314. sentence.append(" ")