Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/europarl_raw.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/util.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__init__.py +186 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/aligned.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/api.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bcp47.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bnc.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bracket_parse.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/categorized_sents.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/chunked.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/cmudict.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/conll.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/crubadan.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/dependency.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ieer.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/indian.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ipipan.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/markdown.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/mte.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/nombank.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/nps_chat.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/opinion_lexicon.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/panlex_lite.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/panlex_swadesh.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/pl196x.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ppattach.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/pros_cons.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/reviews.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/semcor.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/senseval.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/sentiwordnet.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/sinica_treebank.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/string_category.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/tagged.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/timit.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/verbnet.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/wordnet.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ycoe.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/aligned.py +154 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/api.py +516 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bcp47.py +218 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bnc.py +265 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bracket_parse.py +237 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/categorized_sents.py +168 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/chasen.py +158 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/childes.py +630 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/chunked.py +273 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/cmudict.py +88 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/comparative_sents.py +309 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (10.3 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/europarl_raw.cpython-310.pyc
ADDED
|
Binary file (1.19 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (4.54 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__init__.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Corpus Readers
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 5 |
+
# Edward Loper <edloper@gmail.com>
|
| 6 |
+
# URL: <https://www.nltk.org/>
|
| 7 |
+
# For license information, see LICENSE.TXT
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
NLTK corpus readers. The modules in this package provide functions
|
| 11 |
+
that can be used to read corpus fileids in a variety of formats. These
|
| 12 |
+
functions can be used to read both the corpus fileids that are
|
| 13 |
+
distributed in the NLTK corpus package, and corpus fileids that are part
|
| 14 |
+
of external corpora.
|
| 15 |
+
|
| 16 |
+
Corpus Reader Functions
|
| 17 |
+
=======================
|
| 18 |
+
Each corpus module defines one or more "corpus reader functions",
|
| 19 |
+
which can be used to read documents from that corpus. These functions
|
| 20 |
+
take an argument, ``item``, which is used to indicate which document
|
| 21 |
+
should be read from the corpus:
|
| 22 |
+
|
| 23 |
+
- If ``item`` is one of the unique identifiers listed in the corpus
|
| 24 |
+
module's ``items`` variable, then the corresponding document will
|
| 25 |
+
be loaded from the NLTK corpus package.
|
| 26 |
+
- If ``item`` is a fileid, then that file will be read.
|
| 27 |
+
|
| 28 |
+
Additionally, corpus reader functions can be given lists of item
|
| 29 |
+
names; in which case, they will return a concatenation of the
|
| 30 |
+
corresponding documents.
|
| 31 |
+
|
| 32 |
+
Corpus reader functions are named based on the type of information
|
| 33 |
+
they return. Some common examples, and their return types, are:
|
| 34 |
+
|
| 35 |
+
- words(): list of str
|
| 36 |
+
- sents(): list of (list of str)
|
| 37 |
+
- paras(): list of (list of (list of str))
|
| 38 |
+
- tagged_words(): list of (str,str) tuple
|
| 39 |
+
- tagged_sents(): list of (list of (str,str))
|
| 40 |
+
- tagged_paras(): list of (list of (list of (str,str)))
|
| 41 |
+
- chunked_sents(): list of (Tree w/ (str,str) leaves)
|
| 42 |
+
- parsed_sents(): list of (Tree with str leaves)
|
| 43 |
+
- parsed_paras(): list of (list of (Tree with str leaves))
|
| 44 |
+
- xml(): A single xml ElementTree
|
| 45 |
+
- raw(): unprocessed corpus contents
|
| 46 |
+
|
| 47 |
+
For example, to read a list of the words in the Brown Corpus, use
|
| 48 |
+
``nltk.corpus.brown.words()``:
|
| 49 |
+
|
| 50 |
+
>>> from nltk.corpus import brown
|
| 51 |
+
>>> print(", ".join(brown.words()[:6])) # only first 6 words
|
| 52 |
+
The, Fulton, County, Grand, Jury, said
|
| 53 |
+
|
| 54 |
+
isort:skip_file
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
from nltk.corpus.reader.plaintext import *
|
| 58 |
+
from nltk.corpus.reader.util import *
|
| 59 |
+
from nltk.corpus.reader.api import *
|
| 60 |
+
from nltk.corpus.reader.tagged import *
|
| 61 |
+
from nltk.corpus.reader.cmudict import *
|
| 62 |
+
from nltk.corpus.reader.conll import *
|
| 63 |
+
from nltk.corpus.reader.chunked import *
|
| 64 |
+
from nltk.corpus.reader.wordlist import *
|
| 65 |
+
from nltk.corpus.reader.xmldocs import *
|
| 66 |
+
from nltk.corpus.reader.ppattach import *
|
| 67 |
+
from nltk.corpus.reader.senseval import *
|
| 68 |
+
from nltk.corpus.reader.ieer import *
|
| 69 |
+
from nltk.corpus.reader.sinica_treebank import *
|
| 70 |
+
from nltk.corpus.reader.bracket_parse import *
|
| 71 |
+
from nltk.corpus.reader.indian import *
|
| 72 |
+
from nltk.corpus.reader.toolbox import *
|
| 73 |
+
from nltk.corpus.reader.timit import *
|
| 74 |
+
from nltk.corpus.reader.ycoe import *
|
| 75 |
+
from nltk.corpus.reader.rte import *
|
| 76 |
+
from nltk.corpus.reader.string_category import *
|
| 77 |
+
from nltk.corpus.reader.propbank import *
|
| 78 |
+
from nltk.corpus.reader.verbnet import *
|
| 79 |
+
from nltk.corpus.reader.bnc import *
|
| 80 |
+
from nltk.corpus.reader.nps_chat import *
|
| 81 |
+
from nltk.corpus.reader.wordnet import *
|
| 82 |
+
from nltk.corpus.reader.switchboard import *
|
| 83 |
+
from nltk.corpus.reader.dependency import *
|
| 84 |
+
from nltk.corpus.reader.nombank import *
|
| 85 |
+
from nltk.corpus.reader.ipipan import *
|
| 86 |
+
from nltk.corpus.reader.pl196x import *
|
| 87 |
+
from nltk.corpus.reader.knbc import *
|
| 88 |
+
from nltk.corpus.reader.chasen import *
|
| 89 |
+
from nltk.corpus.reader.childes import *
|
| 90 |
+
from nltk.corpus.reader.aligned import *
|
| 91 |
+
from nltk.corpus.reader.lin import *
|
| 92 |
+
from nltk.corpus.reader.semcor import *
|
| 93 |
+
from nltk.corpus.reader.framenet import *
|
| 94 |
+
from nltk.corpus.reader.udhr import *
|
| 95 |
+
from nltk.corpus.reader.bnc import *
|
| 96 |
+
from nltk.corpus.reader.sentiwordnet import *
|
| 97 |
+
from nltk.corpus.reader.twitter import *
|
| 98 |
+
from nltk.corpus.reader.nkjp import *
|
| 99 |
+
from nltk.corpus.reader.crubadan import *
|
| 100 |
+
from nltk.corpus.reader.mte import *
|
| 101 |
+
from nltk.corpus.reader.reviews import *
|
| 102 |
+
from nltk.corpus.reader.opinion_lexicon import *
|
| 103 |
+
from nltk.corpus.reader.pros_cons import *
|
| 104 |
+
from nltk.corpus.reader.categorized_sents import *
|
| 105 |
+
from nltk.corpus.reader.comparative_sents import *
|
| 106 |
+
from nltk.corpus.reader.panlex_lite import *
|
| 107 |
+
from nltk.corpus.reader.panlex_swadesh import *
|
| 108 |
+
from nltk.corpus.reader.bcp47 import *
|
| 109 |
+
|
| 110 |
+
# Make sure that nltk.corpus.reader.bracket_parse gives the module, not
|
| 111 |
+
# the function bracket_parse() defined in nltk.tree:
|
| 112 |
+
from nltk.corpus.reader import bracket_parse
|
| 113 |
+
|
| 114 |
+
__all__ = [
|
| 115 |
+
"CorpusReader",
|
| 116 |
+
"CategorizedCorpusReader",
|
| 117 |
+
"PlaintextCorpusReader",
|
| 118 |
+
"find_corpus_fileids",
|
| 119 |
+
"TaggedCorpusReader",
|
| 120 |
+
"CMUDictCorpusReader",
|
| 121 |
+
"ConllChunkCorpusReader",
|
| 122 |
+
"WordListCorpusReader",
|
| 123 |
+
"PPAttachmentCorpusReader",
|
| 124 |
+
"SensevalCorpusReader",
|
| 125 |
+
"IEERCorpusReader",
|
| 126 |
+
"ChunkedCorpusReader",
|
| 127 |
+
"SinicaTreebankCorpusReader",
|
| 128 |
+
"BracketParseCorpusReader",
|
| 129 |
+
"IndianCorpusReader",
|
| 130 |
+
"ToolboxCorpusReader",
|
| 131 |
+
"TimitCorpusReader",
|
| 132 |
+
"YCOECorpusReader",
|
| 133 |
+
"MacMorphoCorpusReader",
|
| 134 |
+
"SyntaxCorpusReader",
|
| 135 |
+
"AlpinoCorpusReader",
|
| 136 |
+
"RTECorpusReader",
|
| 137 |
+
"StringCategoryCorpusReader",
|
| 138 |
+
"EuroparlCorpusReader",
|
| 139 |
+
"CategorizedBracketParseCorpusReader",
|
| 140 |
+
"CategorizedTaggedCorpusReader",
|
| 141 |
+
"CategorizedPlaintextCorpusReader",
|
| 142 |
+
"PortugueseCategorizedPlaintextCorpusReader",
|
| 143 |
+
"tagged_treebank_para_block_reader",
|
| 144 |
+
"PropbankCorpusReader",
|
| 145 |
+
"VerbnetCorpusReader",
|
| 146 |
+
"BNCCorpusReader",
|
| 147 |
+
"ConllCorpusReader",
|
| 148 |
+
"XMLCorpusReader",
|
| 149 |
+
"NPSChatCorpusReader",
|
| 150 |
+
"SwadeshCorpusReader",
|
| 151 |
+
"WordNetCorpusReader",
|
| 152 |
+
"WordNetICCorpusReader",
|
| 153 |
+
"SwitchboardCorpusReader",
|
| 154 |
+
"DependencyCorpusReader",
|
| 155 |
+
"NombankCorpusReader",
|
| 156 |
+
"IPIPANCorpusReader",
|
| 157 |
+
"Pl196xCorpusReader",
|
| 158 |
+
"TEICorpusView",
|
| 159 |
+
"KNBCorpusReader",
|
| 160 |
+
"ChasenCorpusReader",
|
| 161 |
+
"CHILDESCorpusReader",
|
| 162 |
+
"AlignedCorpusReader",
|
| 163 |
+
"TimitTaggedCorpusReader",
|
| 164 |
+
"LinThesaurusCorpusReader",
|
| 165 |
+
"SemcorCorpusReader",
|
| 166 |
+
"FramenetCorpusReader",
|
| 167 |
+
"UdhrCorpusReader",
|
| 168 |
+
"BNCCorpusReader",
|
| 169 |
+
"SentiWordNetCorpusReader",
|
| 170 |
+
"SentiSynset",
|
| 171 |
+
"TwitterCorpusReader",
|
| 172 |
+
"NKJPCorpusReader",
|
| 173 |
+
"CrubadanCorpusReader",
|
| 174 |
+
"MTECorpusReader",
|
| 175 |
+
"ReviewsCorpusReader",
|
| 176 |
+
"OpinionLexiconCorpusReader",
|
| 177 |
+
"ProsConsCorpusReader",
|
| 178 |
+
"CategorizedSentencesCorpusReader",
|
| 179 |
+
"ComparativeSentencesCorpusReader",
|
| 180 |
+
"PanLexLiteCorpusReader",
|
| 181 |
+
"NonbreakingPrefixesCorpusReader",
|
| 182 |
+
"UnicharsCorpusReader",
|
| 183 |
+
"MWAPPDBCorpusReader",
|
| 184 |
+
"PanlexSwadeshCorpusReader",
|
| 185 |
+
"BCP47CorpusReader",
|
| 186 |
+
]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/aligned.cpython-310.pyc
ADDED
|
Binary file (4.26 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/api.cpython-310.pyc
ADDED
|
Binary file (18.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bcp47.cpython-310.pyc
ADDED
|
Binary file (6.92 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bnc.cpython-310.pyc
ADDED
|
Binary file (9.32 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/bracket_parse.cpython-310.pyc
ADDED
|
Binary file (9.83 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/categorized_sents.cpython-310.pyc
ADDED
|
Binary file (6.01 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/chunked.cpython-310.pyc
ADDED
|
Binary file (8.76 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/cmudict.cpython-310.pyc
ADDED
|
Binary file (3.79 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/conll.cpython-310.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/crubadan.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/dependency.cpython-310.pyc
ADDED
|
Binary file (4.16 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ieer.cpython-310.pyc
ADDED
|
Binary file (3.85 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/indian.cpython-310.pyc
ADDED
|
Binary file (3.64 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ipipan.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/markdown.cpython-310.pyc
ADDED
|
Binary file (14.9 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/mte.cpython-310.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/nombank.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/nps_chat.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/opinion_lexicon.cpython-310.pyc
ADDED
|
Binary file (4.49 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/panlex_lite.cpython-310.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/panlex_swadesh.cpython-310.pyc
ADDED
|
Binary file (4.01 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/pl196x.cpython-310.pyc
ADDED
|
Binary file (8 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ppattach.cpython-310.pyc
ADDED
|
Binary file (3.26 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/pros_cons.cpython-310.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/reviews.cpython-310.pyc
ADDED
|
Binary file (12.1 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/semcor.cpython-310.pyc
ADDED
|
Binary file (9.04 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/senseval.cpython-310.pyc
ADDED
|
Binary file (5.4 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/sentiwordnet.cpython-310.pyc
ADDED
|
Binary file (5.25 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/sinica_treebank.cpython-310.pyc
ADDED
|
Binary file (3.09 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/string_category.cpython-310.pyc
ADDED
|
Binary file (1.95 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/tagged.cpython-310.pyc
ADDED
|
Binary file (10.7 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/timit.cpython-310.pyc
ADDED
|
Binary file (16.6 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/verbnet.cpython-310.pyc
ADDED
|
Binary file (21.3 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/wordnet.cpython-310.pyc
ADDED
|
Binary file (72.5 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/__pycache__/ycoe.cpython-310.pyc
ADDED
|
Binary file (10.9 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/aligned.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Aligned Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# URL: <https://www.nltk.org/>
|
| 5 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
from nltk.corpus.reader.api import CorpusReader
|
| 9 |
+
from nltk.corpus.reader.util import (
|
| 10 |
+
StreamBackedCorpusView,
|
| 11 |
+
concat,
|
| 12 |
+
read_alignedsent_block,
|
| 13 |
+
)
|
| 14 |
+
from nltk.tokenize import RegexpTokenizer, WhitespaceTokenizer
|
| 15 |
+
from nltk.translate import AlignedSent, Alignment
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AlignedCorpusReader(CorpusReader):
|
| 19 |
+
"""
|
| 20 |
+
Reader for corpora of word-aligned sentences. Tokens are assumed
|
| 21 |
+
to be separated by whitespace. Sentences begin on separate lines.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(
|
| 25 |
+
self,
|
| 26 |
+
root,
|
| 27 |
+
fileids,
|
| 28 |
+
sep="/",
|
| 29 |
+
word_tokenizer=WhitespaceTokenizer(),
|
| 30 |
+
sent_tokenizer=RegexpTokenizer("\n", gaps=True),
|
| 31 |
+
alignedsent_block_reader=read_alignedsent_block,
|
| 32 |
+
encoding="latin1",
|
| 33 |
+
):
|
| 34 |
+
"""
|
| 35 |
+
Construct a new Aligned Corpus reader for a set of documents
|
| 36 |
+
located at the given root directory. Example usage:
|
| 37 |
+
|
| 38 |
+
>>> root = '/...path to corpus.../'
|
| 39 |
+
>>> reader = AlignedCorpusReader(root, '.*', '.txt') # doctest: +SKIP
|
| 40 |
+
|
| 41 |
+
:param root: The root directory for this corpus.
|
| 42 |
+
:param fileids: A list or regexp specifying the fileids in this corpus.
|
| 43 |
+
"""
|
| 44 |
+
CorpusReader.__init__(self, root, fileids, encoding)
|
| 45 |
+
self._sep = sep
|
| 46 |
+
self._word_tokenizer = word_tokenizer
|
| 47 |
+
self._sent_tokenizer = sent_tokenizer
|
| 48 |
+
self._alignedsent_block_reader = alignedsent_block_reader
|
| 49 |
+
|
| 50 |
+
def words(self, fileids=None):
|
| 51 |
+
"""
|
| 52 |
+
:return: the given file(s) as a list of words
|
| 53 |
+
and punctuation symbols.
|
| 54 |
+
:rtype: list(str)
|
| 55 |
+
"""
|
| 56 |
+
return concat(
|
| 57 |
+
[
|
| 58 |
+
AlignedSentCorpusView(
|
| 59 |
+
fileid,
|
| 60 |
+
enc,
|
| 61 |
+
False,
|
| 62 |
+
False,
|
| 63 |
+
self._word_tokenizer,
|
| 64 |
+
self._sent_tokenizer,
|
| 65 |
+
self._alignedsent_block_reader,
|
| 66 |
+
)
|
| 67 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 68 |
+
]
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def sents(self, fileids=None):
|
| 72 |
+
"""
|
| 73 |
+
:return: the given file(s) as a list of
|
| 74 |
+
sentences or utterances, each encoded as a list of word
|
| 75 |
+
strings.
|
| 76 |
+
:rtype: list(list(str))
|
| 77 |
+
"""
|
| 78 |
+
return concat(
|
| 79 |
+
[
|
| 80 |
+
AlignedSentCorpusView(
|
| 81 |
+
fileid,
|
| 82 |
+
enc,
|
| 83 |
+
False,
|
| 84 |
+
True,
|
| 85 |
+
self._word_tokenizer,
|
| 86 |
+
self._sent_tokenizer,
|
| 87 |
+
self._alignedsent_block_reader,
|
| 88 |
+
)
|
| 89 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 90 |
+
]
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def aligned_sents(self, fileids=None):
|
| 94 |
+
"""
|
| 95 |
+
:return: the given file(s) as a list of AlignedSent objects.
|
| 96 |
+
:rtype: list(AlignedSent)
|
| 97 |
+
"""
|
| 98 |
+
return concat(
|
| 99 |
+
[
|
| 100 |
+
AlignedSentCorpusView(
|
| 101 |
+
fileid,
|
| 102 |
+
enc,
|
| 103 |
+
True,
|
| 104 |
+
True,
|
| 105 |
+
self._word_tokenizer,
|
| 106 |
+
self._sent_tokenizer,
|
| 107 |
+
self._alignedsent_block_reader,
|
| 108 |
+
)
|
| 109 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 110 |
+
]
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class AlignedSentCorpusView(StreamBackedCorpusView):
|
| 115 |
+
"""
|
| 116 |
+
A specialized corpus view for aligned sentences.
|
| 117 |
+
``AlignedSentCorpusView`` objects are typically created by
|
| 118 |
+
``AlignedCorpusReader`` (not directly by nltk users).
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
corpus_file,
|
| 124 |
+
encoding,
|
| 125 |
+
aligned,
|
| 126 |
+
group_by_sent,
|
| 127 |
+
word_tokenizer,
|
| 128 |
+
sent_tokenizer,
|
| 129 |
+
alignedsent_block_reader,
|
| 130 |
+
):
|
| 131 |
+
self._aligned = aligned
|
| 132 |
+
self._group_by_sent = group_by_sent
|
| 133 |
+
self._word_tokenizer = word_tokenizer
|
| 134 |
+
self._sent_tokenizer = sent_tokenizer
|
| 135 |
+
self._alignedsent_block_reader = alignedsent_block_reader
|
| 136 |
+
StreamBackedCorpusView.__init__(self, corpus_file, encoding=encoding)
|
| 137 |
+
|
| 138 |
+
def read_block(self, stream):
|
| 139 |
+
block = [
|
| 140 |
+
self._word_tokenizer.tokenize(sent_str)
|
| 141 |
+
for alignedsent_str in self._alignedsent_block_reader(stream)
|
| 142 |
+
for sent_str in self._sent_tokenizer.tokenize(alignedsent_str)
|
| 143 |
+
]
|
| 144 |
+
if self._aligned:
|
| 145 |
+
block[2] = Alignment.fromstring(
|
| 146 |
+
" ".join(block[2])
|
| 147 |
+
) # kludge; we shouldn't have tokenized the alignment string
|
| 148 |
+
block = [AlignedSent(*block)]
|
| 149 |
+
elif self._group_by_sent:
|
| 150 |
+
block = [block[0]]
|
| 151 |
+
else:
|
| 152 |
+
block = block[0]
|
| 153 |
+
|
| 154 |
+
return block
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/api.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: API for Corpus Readers
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 5 |
+
# Edward Loper <edloper@gmail.com>
|
| 6 |
+
# URL: <https://www.nltk.org/>
|
| 7 |
+
# For license information, see LICENSE.TXT
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
API for corpus readers.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
import re
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
from itertools import chain
|
| 17 |
+
|
| 18 |
+
from nltk.corpus.reader.util import *
|
| 19 |
+
from nltk.data import FileSystemPathPointer, PathPointer, ZipFilePathPointer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class CorpusReader:
|
| 23 |
+
"""
|
| 24 |
+
A base class for "corpus reader" classes, each of which can be
|
| 25 |
+
used to read a specific corpus format. Each individual corpus
|
| 26 |
+
reader instance is used to read a specific corpus, consisting of
|
| 27 |
+
one or more files under a common root directory. Each file is
|
| 28 |
+
identified by its ``file identifier``, which is the relative path
|
| 29 |
+
to the file from the root directory.
|
| 30 |
+
|
| 31 |
+
A separate subclass is defined for each corpus format. These
|
| 32 |
+
subclasses define one or more methods that provide 'views' on the
|
| 33 |
+
corpus contents, such as ``words()`` (for a list of words) and
|
| 34 |
+
``parsed_sents()`` (for a list of parsed sentences). Called with
|
| 35 |
+
no arguments, these methods will return the contents of the entire
|
| 36 |
+
corpus. For most corpora, these methods define one or more
|
| 37 |
+
selection arguments, such as ``fileids`` or ``categories``, which can
|
| 38 |
+
be used to select which portion of the corpus should be returned.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, root, fileids, encoding="utf8", tagset=None):
|
| 42 |
+
"""
|
| 43 |
+
:type root: PathPointer or str
|
| 44 |
+
:param root: A path pointer identifying the root directory for
|
| 45 |
+
this corpus. If a string is specified, then it will be
|
| 46 |
+
converted to a ``PathPointer`` automatically.
|
| 47 |
+
:param fileids: A list of the files that make up this corpus.
|
| 48 |
+
This list can either be specified explicitly, as a list of
|
| 49 |
+
strings; or implicitly, as a regular expression over file
|
| 50 |
+
paths. The absolute path for each file will be constructed
|
| 51 |
+
by joining the reader's root to each file name.
|
| 52 |
+
:param encoding: The default unicode encoding for the files
|
| 53 |
+
that make up the corpus. The value of ``encoding`` can be any
|
| 54 |
+
of the following:
|
| 55 |
+
|
| 56 |
+
- A string: ``encoding`` is the encoding name for all files.
|
| 57 |
+
- A dictionary: ``encoding[file_id]`` is the encoding
|
| 58 |
+
name for the file whose identifier is ``file_id``. If
|
| 59 |
+
``file_id`` is not in ``encoding``, then the file
|
| 60 |
+
contents will be processed using non-unicode byte strings.
|
| 61 |
+
- A list: ``encoding`` should be a list of ``(regexp, encoding)``
|
| 62 |
+
tuples. The encoding for a file whose identifier is ``file_id``
|
| 63 |
+
will be the ``encoding`` value for the first tuple whose
|
| 64 |
+
``regexp`` matches the ``file_id``. If no tuple's ``regexp``
|
| 65 |
+
matches the ``file_id``, the file contents will be processed
|
| 66 |
+
using non-unicode byte strings.
|
| 67 |
+
- None: the file contents of all files will be
|
| 68 |
+
processed using non-unicode byte strings.
|
| 69 |
+
:param tagset: The name of the tagset used by this corpus, to be used
|
| 70 |
+
for normalizing or converting the POS tags returned by the
|
| 71 |
+
``tagged_...()`` methods.
|
| 72 |
+
"""
|
| 73 |
+
# Convert the root to a path pointer, if necessary.
|
| 74 |
+
if isinstance(root, str) and not isinstance(root, PathPointer):
|
| 75 |
+
m = re.match(r"(.*\.zip)/?(.*)$|", root)
|
| 76 |
+
zipfile, zipentry = m.groups()
|
| 77 |
+
if zipfile:
|
| 78 |
+
root = ZipFilePathPointer(zipfile, zipentry)
|
| 79 |
+
else:
|
| 80 |
+
root = FileSystemPathPointer(root)
|
| 81 |
+
elif not isinstance(root, PathPointer):
|
| 82 |
+
raise TypeError("CorpusReader: expected a string or a PathPointer")
|
| 83 |
+
|
| 84 |
+
# If `fileids` is a regexp, then expand it.
|
| 85 |
+
if isinstance(fileids, str):
|
| 86 |
+
fileids = find_corpus_fileids(root, fileids)
|
| 87 |
+
|
| 88 |
+
self._fileids = fileids
|
| 89 |
+
"""A list of the relative paths for the fileids that make up
|
| 90 |
+
this corpus."""
|
| 91 |
+
|
| 92 |
+
self._root = root
|
| 93 |
+
"""The root directory for this corpus."""
|
| 94 |
+
|
| 95 |
+
self._readme = "README"
|
| 96 |
+
self._license = "LICENSE"
|
| 97 |
+
self._citation = "citation.bib"
|
| 98 |
+
|
| 99 |
+
# If encoding was specified as a list of regexps, then convert
|
| 100 |
+
# it to a dictionary.
|
| 101 |
+
if isinstance(encoding, list):
|
| 102 |
+
encoding_dict = {}
|
| 103 |
+
for fileid in self._fileids:
|
| 104 |
+
for x in encoding:
|
| 105 |
+
(regexp, enc) = x
|
| 106 |
+
if re.match(regexp, fileid):
|
| 107 |
+
encoding_dict[fileid] = enc
|
| 108 |
+
break
|
| 109 |
+
encoding = encoding_dict
|
| 110 |
+
|
| 111 |
+
self._encoding = encoding
|
| 112 |
+
"""The default unicode encoding for the fileids that make up
|
| 113 |
+
this corpus. If ``encoding`` is None, then the file
|
| 114 |
+
contents are processed using byte strings."""
|
| 115 |
+
self._tagset = tagset
|
| 116 |
+
|
| 117 |
+
def __repr__(self):
|
| 118 |
+
if isinstance(self._root, ZipFilePathPointer):
|
| 119 |
+
path = f"{self._root.zipfile.filename}/{self._root.entry}"
|
| 120 |
+
else:
|
| 121 |
+
path = "%s" % self._root.path
|
| 122 |
+
return f"<{self.__class__.__name__} in {path!r}>"
|
| 123 |
+
|
| 124 |
+
def ensure_loaded(self):
|
| 125 |
+
"""
|
| 126 |
+
Load this corpus (if it has not already been loaded). This is
|
| 127 |
+
used by LazyCorpusLoader as a simple method that can be used to
|
| 128 |
+
make sure a corpus is loaded -- e.g., in case a user wants to
|
| 129 |
+
do help(some_corpus).
|
| 130 |
+
"""
|
| 131 |
+
pass # no need to actually do anything.
|
| 132 |
+
|
| 133 |
+
def readme(self):
|
| 134 |
+
"""
|
| 135 |
+
Return the contents of the corpus README file, if it exists.
|
| 136 |
+
"""
|
| 137 |
+
with self.open(self._readme) as f:
|
| 138 |
+
return f.read()
|
| 139 |
+
|
| 140 |
+
def license(self):
|
| 141 |
+
"""
|
| 142 |
+
Return the contents of the corpus LICENSE file, if it exists.
|
| 143 |
+
"""
|
| 144 |
+
with self.open(self._license) as f:
|
| 145 |
+
return f.read()
|
| 146 |
+
|
| 147 |
+
def citation(self):
|
| 148 |
+
"""
|
| 149 |
+
Return the contents of the corpus citation.bib file, if it exists.
|
| 150 |
+
"""
|
| 151 |
+
with self.open(self._citation) as f:
|
| 152 |
+
return f.read()
|
| 153 |
+
|
| 154 |
+
def fileids(self):
|
| 155 |
+
"""
|
| 156 |
+
Return a list of file identifiers for the fileids that make up
|
| 157 |
+
this corpus.
|
| 158 |
+
"""
|
| 159 |
+
return self._fileids
|
| 160 |
+
|
| 161 |
+
def abspath(self, fileid):
|
| 162 |
+
"""
|
| 163 |
+
Return the absolute path for the given file.
|
| 164 |
+
|
| 165 |
+
:type fileid: str
|
| 166 |
+
:param fileid: The file identifier for the file whose path
|
| 167 |
+
should be returned.
|
| 168 |
+
:rtype: PathPointer
|
| 169 |
+
"""
|
| 170 |
+
return self._root.join(fileid)
|
| 171 |
+
|
| 172 |
+
def abspaths(self, fileids=None, include_encoding=False, include_fileid=False):
|
| 173 |
+
"""
|
| 174 |
+
Return a list of the absolute paths for all fileids in this corpus;
|
| 175 |
+
or for the given list of fileids, if specified.
|
| 176 |
+
|
| 177 |
+
:type fileids: None or str or list
|
| 178 |
+
:param fileids: Specifies the set of fileids for which paths should
|
| 179 |
+
be returned. Can be None, for all fileids; a list of
|
| 180 |
+
file identifiers, for a specified set of fileids; or a single
|
| 181 |
+
file identifier, for a single file. Note that the return
|
| 182 |
+
value is always a list of paths, even if ``fileids`` is a
|
| 183 |
+
single file identifier.
|
| 184 |
+
|
| 185 |
+
:param include_encoding: If true, then return a list of
|
| 186 |
+
``(path_pointer, encoding)`` tuples.
|
| 187 |
+
|
| 188 |
+
:rtype: list(PathPointer)
|
| 189 |
+
"""
|
| 190 |
+
if fileids is None:
|
| 191 |
+
fileids = self._fileids
|
| 192 |
+
elif isinstance(fileids, str):
|
| 193 |
+
fileids = [fileids]
|
| 194 |
+
|
| 195 |
+
paths = [self._root.join(f) for f in fileids]
|
| 196 |
+
|
| 197 |
+
if include_encoding and include_fileid:
|
| 198 |
+
return list(zip(paths, [self.encoding(f) for f in fileids], fileids))
|
| 199 |
+
elif include_fileid:
|
| 200 |
+
return list(zip(paths, fileids))
|
| 201 |
+
elif include_encoding:
|
| 202 |
+
return list(zip(paths, [self.encoding(f) for f in fileids]))
|
| 203 |
+
else:
|
| 204 |
+
return paths
|
| 205 |
+
|
| 206 |
+
def raw(self, fileids=None):
|
| 207 |
+
"""
|
| 208 |
+
:param fileids: A list specifying the fileids that should be used.
|
| 209 |
+
:return: the given file(s) as a single string.
|
| 210 |
+
:rtype: str
|
| 211 |
+
"""
|
| 212 |
+
if fileids is None:
|
| 213 |
+
fileids = self._fileids
|
| 214 |
+
elif isinstance(fileids, str):
|
| 215 |
+
fileids = [fileids]
|
| 216 |
+
contents = []
|
| 217 |
+
for f in fileids:
|
| 218 |
+
with self.open(f) as fp:
|
| 219 |
+
contents.append(fp.read())
|
| 220 |
+
return concat(contents)
|
| 221 |
+
|
| 222 |
+
def open(self, file):
|
| 223 |
+
"""
|
| 224 |
+
Return an open stream that can be used to read the given file.
|
| 225 |
+
If the file's encoding is not None, then the stream will
|
| 226 |
+
automatically decode the file's contents into unicode.
|
| 227 |
+
|
| 228 |
+
:param file: The file identifier of the file to read.
|
| 229 |
+
"""
|
| 230 |
+
encoding = self.encoding(file)
|
| 231 |
+
stream = self._root.join(file).open(encoding)
|
| 232 |
+
return stream
|
| 233 |
+
|
| 234 |
+
def encoding(self, file):
|
| 235 |
+
"""
|
| 236 |
+
Return the unicode encoding for the given corpus file, if known.
|
| 237 |
+
If the encoding is unknown, or if the given file should be
|
| 238 |
+
processed using byte strings (str), then return None.
|
| 239 |
+
"""
|
| 240 |
+
if isinstance(self._encoding, dict):
|
| 241 |
+
return self._encoding.get(file)
|
| 242 |
+
else:
|
| 243 |
+
return self._encoding
|
| 244 |
+
|
| 245 |
+
def _get_root(self):
|
| 246 |
+
return self._root
|
| 247 |
+
|
| 248 |
+
root = property(
|
| 249 |
+
_get_root,
|
| 250 |
+
doc="""
|
| 251 |
+
The directory where this corpus is stored.
|
| 252 |
+
|
| 253 |
+
:type: PathPointer""",
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
######################################################################
|
| 258 |
+
# { Corpora containing categorized items
|
| 259 |
+
######################################################################
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class CategorizedCorpusReader:
|
| 263 |
+
"""
|
| 264 |
+
A mixin class used to aid in the implementation of corpus readers
|
| 265 |
+
for categorized corpora. This class defines the method
|
| 266 |
+
``categories()``, which returns a list of the categories for the
|
| 267 |
+
corpus or for a specified set of fileids; and overrides ``fileids()``
|
| 268 |
+
to take a ``categories`` argument, restricting the set of fileids to
|
| 269 |
+
be returned.
|
| 270 |
+
|
| 271 |
+
Subclasses are expected to:
|
| 272 |
+
|
| 273 |
+
- Call ``__init__()`` to set up the mapping.
|
| 274 |
+
|
| 275 |
+
- Override all view methods to accept a ``categories`` parameter,
|
| 276 |
+
which can be used *instead* of the ``fileids`` parameter, to
|
| 277 |
+
select which fileids should be included in the returned view.
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(self, kwargs):
|
| 281 |
+
"""
|
| 282 |
+
Initialize this mapping based on keyword arguments, as
|
| 283 |
+
follows:
|
| 284 |
+
|
| 285 |
+
- cat_pattern: A regular expression pattern used to find the
|
| 286 |
+
category for each file identifier. The pattern will be
|
| 287 |
+
applied to each file identifier, and the first matching
|
| 288 |
+
group will be used as the category label for that file.
|
| 289 |
+
|
| 290 |
+
- cat_map: A dictionary, mapping from file identifiers to
|
| 291 |
+
category labels.
|
| 292 |
+
|
| 293 |
+
- cat_file: The name of a file that contains the mapping
|
| 294 |
+
from file identifiers to categories. The argument
|
| 295 |
+
``cat_delimiter`` can be used to specify a delimiter.
|
| 296 |
+
|
| 297 |
+
The corresponding argument will be deleted from ``kwargs``. If
|
| 298 |
+
more than one argument is specified, an exception will be
|
| 299 |
+
raised.
|
| 300 |
+
"""
|
| 301 |
+
self._f2c = None #: file-to-category mapping
|
| 302 |
+
self._c2f = None #: category-to-file mapping
|
| 303 |
+
|
| 304 |
+
self._pattern = None #: regexp specifying the mapping
|
| 305 |
+
self._map = None #: dict specifying the mapping
|
| 306 |
+
self._file = None #: fileid of file containing the mapping
|
| 307 |
+
self._delimiter = None #: delimiter for ``self._file``
|
| 308 |
+
|
| 309 |
+
if "cat_pattern" in kwargs:
|
| 310 |
+
self._pattern = kwargs["cat_pattern"]
|
| 311 |
+
del kwargs["cat_pattern"]
|
| 312 |
+
elif "cat_map" in kwargs:
|
| 313 |
+
self._map = kwargs["cat_map"]
|
| 314 |
+
del kwargs["cat_map"]
|
| 315 |
+
elif "cat_file" in kwargs:
|
| 316 |
+
self._file = kwargs["cat_file"]
|
| 317 |
+
del kwargs["cat_file"]
|
| 318 |
+
if "cat_delimiter" in kwargs:
|
| 319 |
+
self._delimiter = kwargs["cat_delimiter"]
|
| 320 |
+
del kwargs["cat_delimiter"]
|
| 321 |
+
else:
|
| 322 |
+
raise ValueError(
|
| 323 |
+
"Expected keyword argument cat_pattern or " "cat_map or cat_file."
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
if "cat_pattern" in kwargs or "cat_map" in kwargs or "cat_file" in kwargs:
|
| 327 |
+
raise ValueError(
|
| 328 |
+
"Specify exactly one of: cat_pattern, " "cat_map, cat_file."
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
def _init(self):
|
| 332 |
+
self._f2c = defaultdict(set)
|
| 333 |
+
self._c2f = defaultdict(set)
|
| 334 |
+
|
| 335 |
+
if self._pattern is not None:
|
| 336 |
+
for file_id in self._fileids:
|
| 337 |
+
category = re.match(self._pattern, file_id).group(1)
|
| 338 |
+
self._add(file_id, category)
|
| 339 |
+
|
| 340 |
+
elif self._map is not None:
|
| 341 |
+
for (file_id, categories) in self._map.items():
|
| 342 |
+
for category in categories:
|
| 343 |
+
self._add(file_id, category)
|
| 344 |
+
|
| 345 |
+
elif self._file is not None:
|
| 346 |
+
with self.open(self._file) as f:
|
| 347 |
+
for line in f.readlines():
|
| 348 |
+
line = line.strip()
|
| 349 |
+
file_id, categories = line.split(self._delimiter, 1)
|
| 350 |
+
if file_id not in self.fileids():
|
| 351 |
+
raise ValueError(
|
| 352 |
+
"In category mapping file %s: %s "
|
| 353 |
+
"not found" % (self._file, file_id)
|
| 354 |
+
)
|
| 355 |
+
for category in categories.split(self._delimiter):
|
| 356 |
+
self._add(file_id, category)
|
| 357 |
+
|
| 358 |
+
def _add(self, file_id, category):
|
| 359 |
+
self._f2c[file_id].add(category)
|
| 360 |
+
self._c2f[category].add(file_id)
|
| 361 |
+
|
| 362 |
+
def categories(self, fileids=None):
|
| 363 |
+
"""
|
| 364 |
+
Return a list of the categories that are defined for this corpus,
|
| 365 |
+
or for the file(s) if it is given.
|
| 366 |
+
"""
|
| 367 |
+
if self._f2c is None:
|
| 368 |
+
self._init()
|
| 369 |
+
if fileids is None:
|
| 370 |
+
return sorted(self._c2f)
|
| 371 |
+
if isinstance(fileids, str):
|
| 372 |
+
fileids = [fileids]
|
| 373 |
+
return sorted(set.union(*(self._f2c[d] for d in fileids)))
|
| 374 |
+
|
| 375 |
+
def fileids(self, categories=None):
|
| 376 |
+
"""
|
| 377 |
+
Return a list of file identifiers for the files that make up
|
| 378 |
+
this corpus, or that make up the given category(s) if specified.
|
| 379 |
+
"""
|
| 380 |
+
if categories is None:
|
| 381 |
+
return super().fileids()
|
| 382 |
+
elif isinstance(categories, str):
|
| 383 |
+
if self._f2c is None:
|
| 384 |
+
self._init()
|
| 385 |
+
if categories in self._c2f:
|
| 386 |
+
return sorted(self._c2f[categories])
|
| 387 |
+
else:
|
| 388 |
+
raise ValueError("Category %s not found" % categories)
|
| 389 |
+
else:
|
| 390 |
+
if self._f2c is None:
|
| 391 |
+
self._init()
|
| 392 |
+
return sorted(set.union(*(self._c2f[c] for c in categories)))
|
| 393 |
+
|
| 394 |
+
def _resolve(self, fileids, categories):
|
| 395 |
+
if fileids is not None and categories is not None:
|
| 396 |
+
raise ValueError("Specify fileids or categories, not both")
|
| 397 |
+
if categories is not None:
|
| 398 |
+
return self.fileids(categories)
|
| 399 |
+
else:
|
| 400 |
+
return fileids
|
| 401 |
+
|
| 402 |
+
def raw(self, fileids=None, categories=None):
|
| 403 |
+
return super().raw(self._resolve(fileids, categories))
|
| 404 |
+
|
| 405 |
+
def words(self, fileids=None, categories=None):
|
| 406 |
+
return super().words(self._resolve(fileids, categories))
|
| 407 |
+
|
| 408 |
+
def sents(self, fileids=None, categories=None):
|
| 409 |
+
return super().sents(self._resolve(fileids, categories))
|
| 410 |
+
|
| 411 |
+
def paras(self, fileids=None, categories=None):
|
| 412 |
+
return super().paras(self._resolve(fileids, categories))
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
######################################################################
|
| 416 |
+
# { Treebank readers
|
| 417 |
+
######################################################################
|
| 418 |
+
|
| 419 |
+
# [xx] is it worth it to factor this out?
|
| 420 |
+
class SyntaxCorpusReader(CorpusReader):
|
| 421 |
+
"""
|
| 422 |
+
An abstract base class for reading corpora consisting of
|
| 423 |
+
syntactically parsed text. Subclasses should define:
|
| 424 |
+
|
| 425 |
+
- ``__init__``, which specifies the location of the corpus
|
| 426 |
+
and a method for detecting the sentence blocks in corpus files.
|
| 427 |
+
- ``_read_block``, which reads a block from the input stream.
|
| 428 |
+
- ``_word``, which takes a block and returns a list of list of words.
|
| 429 |
+
- ``_tag``, which takes a block and returns a list of list of tagged
|
| 430 |
+
words.
|
| 431 |
+
- ``_parse``, which takes a block and returns a list of parsed
|
| 432 |
+
sentences.
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
def _parse(self, s):
|
| 436 |
+
raise NotImplementedError()
|
| 437 |
+
|
| 438 |
+
def _word(self, s):
|
| 439 |
+
raise NotImplementedError()
|
| 440 |
+
|
| 441 |
+
def _tag(self, s):
|
| 442 |
+
raise NotImplementedError()
|
| 443 |
+
|
| 444 |
+
def _read_block(self, stream):
|
| 445 |
+
raise NotImplementedError()
|
| 446 |
+
|
| 447 |
+
def parsed_sents(self, fileids=None):
|
| 448 |
+
reader = self._read_parsed_sent_block
|
| 449 |
+
return concat(
|
| 450 |
+
[
|
| 451 |
+
StreamBackedCorpusView(fileid, reader, encoding=enc)
|
| 452 |
+
for fileid, enc in self.abspaths(fileids, True)
|
| 453 |
+
]
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def tagged_sents(self, fileids=None, tagset=None):
|
| 457 |
+
def reader(stream):
|
| 458 |
+
return self._read_tagged_sent_block(stream, tagset)
|
| 459 |
+
|
| 460 |
+
return concat(
|
| 461 |
+
[
|
| 462 |
+
StreamBackedCorpusView(fileid, reader, encoding=enc)
|
| 463 |
+
for fileid, enc in self.abspaths(fileids, True)
|
| 464 |
+
]
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
def sents(self, fileids=None):
|
| 468 |
+
reader = self._read_sent_block
|
| 469 |
+
return concat(
|
| 470 |
+
[
|
| 471 |
+
StreamBackedCorpusView(fileid, reader, encoding=enc)
|
| 472 |
+
for fileid, enc in self.abspaths(fileids, True)
|
| 473 |
+
]
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
def tagged_words(self, fileids=None, tagset=None):
|
| 477 |
+
def reader(stream):
|
| 478 |
+
return self._read_tagged_word_block(stream, tagset)
|
| 479 |
+
|
| 480 |
+
return concat(
|
| 481 |
+
[
|
| 482 |
+
StreamBackedCorpusView(fileid, reader, encoding=enc)
|
| 483 |
+
for fileid, enc in self.abspaths(fileids, True)
|
| 484 |
+
]
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
def words(self, fileids=None):
|
| 488 |
+
return concat(
|
| 489 |
+
[
|
| 490 |
+
StreamBackedCorpusView(fileid, self._read_word_block, encoding=enc)
|
| 491 |
+
for fileid, enc in self.abspaths(fileids, True)
|
| 492 |
+
]
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
# ------------------------------------------------------------
|
| 496 |
+
# { Block Readers
|
| 497 |
+
|
| 498 |
+
def _read_word_block(self, stream):
|
| 499 |
+
return list(chain.from_iterable(self._read_sent_block(stream)))
|
| 500 |
+
|
| 501 |
+
def _read_tagged_word_block(self, stream, tagset=None):
|
| 502 |
+
return list(chain.from_iterable(self._read_tagged_sent_block(stream, tagset)))
|
| 503 |
+
|
| 504 |
+
def _read_sent_block(self, stream):
|
| 505 |
+
return list(filter(None, [self._word(t) for t in self._read_block(stream)]))
|
| 506 |
+
|
| 507 |
+
def _read_tagged_sent_block(self, stream, tagset=None):
|
| 508 |
+
return list(
|
| 509 |
+
filter(None, [self._tag(t, tagset) for t in self._read_block(stream)])
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
def _read_parsed_sent_block(self, stream):
|
| 513 |
+
return list(filter(None, [self._parse(t) for t in self._read_block(stream)]))
|
| 514 |
+
|
| 515 |
+
# } End of Block Readers
|
| 516 |
+
# ------------------------------------------------------------
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bcp47.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: BCP-47 language tags
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2022-2023 NLTK Project
|
| 4 |
+
# Author: Eric Kafe <kafe.eric@gmail.com>
|
| 5 |
+
# URL: <https://www.nltk.org/>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
import re
|
| 9 |
+
from warnings import warn
|
| 10 |
+
from xml.etree import ElementTree as et
|
| 11 |
+
|
| 12 |
+
from nltk.corpus.reader import CorpusReader
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BCP47CorpusReader(CorpusReader):
|
| 16 |
+
"""
|
| 17 |
+
Parse BCP-47 composite language tags
|
| 18 |
+
|
| 19 |
+
Supports all the main subtags, and the 'u-sd' extension:
|
| 20 |
+
|
| 21 |
+
>>> from nltk.corpus import bcp47
|
| 22 |
+
>>> bcp47.name('oc-gascon-u-sd-fr64')
|
| 23 |
+
'Occitan (post 1500): Gascon: Pyrénées-Atlantiques'
|
| 24 |
+
|
| 25 |
+
Can load a conversion table to Wikidata Q-codes:
|
| 26 |
+
>>> bcp47.load_wiki_q()
|
| 27 |
+
>>> bcp47.wiki_q['en-GI-spanglis']
|
| 28 |
+
'Q79388'
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, root, fileids):
|
| 33 |
+
"""Read the BCP-47 database"""
|
| 34 |
+
super().__init__(root, fileids)
|
| 35 |
+
self.langcode = {}
|
| 36 |
+
with self.open("iana/language-subtag-registry.txt") as fp:
|
| 37 |
+
self.db = self.data_dict(fp.read().split("%%\n"))
|
| 38 |
+
with self.open("cldr/common-subdivisions-en.xml") as fp:
|
| 39 |
+
self.subdiv = self.subdiv_dict(
|
| 40 |
+
et.parse(fp).iterfind("localeDisplayNames/subdivisions/subdivision")
|
| 41 |
+
)
|
| 42 |
+
self.morphology()
|
| 43 |
+
|
| 44 |
+
def load_wiki_q(self):
|
| 45 |
+
"""Load conversion table to Wikidata Q-codes (only if needed)"""
|
| 46 |
+
with self.open("cldr/tools-cldr-rdf-external-entityToCode.tsv") as fp:
|
| 47 |
+
self.wiki_q = self.wiki_dict(fp.read().strip().split("\n")[1:])
|
| 48 |
+
|
| 49 |
+
def wiki_dict(self, lines):
|
| 50 |
+
"""Convert Wikidata list of Q-codes to a BCP-47 dictionary"""
|
| 51 |
+
return {
|
| 52 |
+
pair[1]: pair[0].split("/")[-1]
|
| 53 |
+
for pair in [line.strip().split("\t") for line in lines]
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
def subdiv_dict(self, subdivs):
|
| 57 |
+
"""Convert the CLDR subdivisions list to a dictionary"""
|
| 58 |
+
return {sub.attrib["type"]: sub.text for sub in subdivs}
|
| 59 |
+
|
| 60 |
+
def morphology(self):
|
| 61 |
+
self.casing = {
|
| 62 |
+
"language": str.lower,
|
| 63 |
+
"extlang": str.lower,
|
| 64 |
+
"script": str.title,
|
| 65 |
+
"region": str.upper,
|
| 66 |
+
"variant": str.lower,
|
| 67 |
+
}
|
| 68 |
+
dig = "[0-9]"
|
| 69 |
+
low = "[a-z]"
|
| 70 |
+
up = "[A-Z]"
|
| 71 |
+
alnum = "[a-zA-Z0-9]"
|
| 72 |
+
self.format = {
|
| 73 |
+
"language": re.compile(f"{low*3}?"),
|
| 74 |
+
"extlang": re.compile(f"{low*3}"),
|
| 75 |
+
"script": re.compile(f"{up}{low*3}"),
|
| 76 |
+
"region": re.compile(f"({up*2})|({dig*3})"),
|
| 77 |
+
"variant": re.compile(f"{alnum*4}{(alnum+'?')*4}"),
|
| 78 |
+
"singleton": re.compile(f"{low}"),
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
def data_dict(self, records):
|
| 82 |
+
"""Convert the BCP-47 language subtag registry to a dictionary"""
|
| 83 |
+
self.version = records[0].replace("File-Date:", "").strip()
|
| 84 |
+
dic = {}
|
| 85 |
+
dic["deprecated"] = {}
|
| 86 |
+
for label in [
|
| 87 |
+
"language",
|
| 88 |
+
"extlang",
|
| 89 |
+
"script",
|
| 90 |
+
"region",
|
| 91 |
+
"variant",
|
| 92 |
+
"redundant",
|
| 93 |
+
"grandfathered",
|
| 94 |
+
]:
|
| 95 |
+
dic["deprecated"][label] = {}
|
| 96 |
+
for record in records[1:]:
|
| 97 |
+
fields = [field.split(": ") for field in record.strip().split("\n")]
|
| 98 |
+
typ = fields[0][1]
|
| 99 |
+
tag = fields[1][1]
|
| 100 |
+
if typ not in dic:
|
| 101 |
+
dic[typ] = {}
|
| 102 |
+
subfields = {}
|
| 103 |
+
for field in fields[2:]:
|
| 104 |
+
if len(field) == 2:
|
| 105 |
+
[key, val] = field
|
| 106 |
+
if key not in subfields:
|
| 107 |
+
subfields[key] = [val]
|
| 108 |
+
else: # multiple value
|
| 109 |
+
subfields[key].append(val)
|
| 110 |
+
else: # multiline field
|
| 111 |
+
subfields[key][-1] += " " + field[0].strip()
|
| 112 |
+
if (
|
| 113 |
+
"Deprecated" not in record
|
| 114 |
+
and typ == "language"
|
| 115 |
+
and key == "Description"
|
| 116 |
+
):
|
| 117 |
+
self.langcode[subfields[key][-1]] = tag
|
| 118 |
+
for key in subfields:
|
| 119 |
+
if len(subfields[key]) == 1: # single value
|
| 120 |
+
subfields[key] = subfields[key][0]
|
| 121 |
+
if "Deprecated" in record:
|
| 122 |
+
dic["deprecated"][typ][tag] = subfields
|
| 123 |
+
else:
|
| 124 |
+
dic[typ][tag] = subfields
|
| 125 |
+
return dic
|
| 126 |
+
|
| 127 |
+
def val2str(self, val):
|
| 128 |
+
"""Return only first value"""
|
| 129 |
+
if type(val) == list:
|
| 130 |
+
# val = "/".join(val) # Concatenate all values
|
| 131 |
+
val = val[0]
|
| 132 |
+
return val
|
| 133 |
+
|
| 134 |
+
def lang2str(self, lg_record):
|
| 135 |
+
"""Concatenate subtag values"""
|
| 136 |
+
name = f"{lg_record['language']}"
|
| 137 |
+
for label in ["extlang", "script", "region", "variant", "extension"]:
|
| 138 |
+
if label in lg_record:
|
| 139 |
+
name += f": {lg_record[label]}"
|
| 140 |
+
return name
|
| 141 |
+
|
| 142 |
+
def parse_tag(self, tag):
|
| 143 |
+
"""Convert a BCP-47 tag to a dictionary of labelled subtags"""
|
| 144 |
+
subtags = tag.split("-")
|
| 145 |
+
lang = {}
|
| 146 |
+
labels = ["language", "extlang", "script", "region", "variant", "variant"]
|
| 147 |
+
while subtags and labels:
|
| 148 |
+
subtag = subtags.pop(0)
|
| 149 |
+
found = False
|
| 150 |
+
while labels:
|
| 151 |
+
label = labels.pop(0)
|
| 152 |
+
subtag = self.casing[label](subtag)
|
| 153 |
+
if self.format[label].fullmatch(subtag):
|
| 154 |
+
if subtag in self.db[label]:
|
| 155 |
+
found = True
|
| 156 |
+
valstr = self.val2str(self.db[label][subtag]["Description"])
|
| 157 |
+
if label == "variant" and label in lang:
|
| 158 |
+
lang[label] += ": " + valstr
|
| 159 |
+
else:
|
| 160 |
+
lang[label] = valstr
|
| 161 |
+
break
|
| 162 |
+
elif subtag in self.db["deprecated"][label]:
|
| 163 |
+
found = True
|
| 164 |
+
note = f"The {subtag!r} {label} code is deprecated"
|
| 165 |
+
if "Preferred-Value" in self.db["deprecated"][label][subtag]:
|
| 166 |
+
prefer = self.db["deprecated"][label][subtag][
|
| 167 |
+
"Preferred-Value"
|
| 168 |
+
]
|
| 169 |
+
note += f"', prefer '{self.val2str(prefer)}'"
|
| 170 |
+
lang[label] = self.val2str(
|
| 171 |
+
self.db["deprecated"][label][subtag]["Description"]
|
| 172 |
+
)
|
| 173 |
+
warn(note)
|
| 174 |
+
break
|
| 175 |
+
if not found:
|
| 176 |
+
if subtag == "u" and subtags[0] == "sd": # CLDR regional subdivisions
|
| 177 |
+
sd = subtags[1]
|
| 178 |
+
if sd in self.subdiv:
|
| 179 |
+
ext = self.subdiv[sd]
|
| 180 |
+
else:
|
| 181 |
+
ext = f"<Unknown subdivision: {ext}>"
|
| 182 |
+
else: # other extension subtags are not supported yet
|
| 183 |
+
ext = f"{subtag}{''.join(['-'+ext for ext in subtags])}".lower()
|
| 184 |
+
if not self.format["singleton"].fullmatch(subtag):
|
| 185 |
+
ext = f"<Invalid extension: {ext}>"
|
| 186 |
+
warn(ext)
|
| 187 |
+
lang["extension"] = ext
|
| 188 |
+
subtags = []
|
| 189 |
+
return lang
|
| 190 |
+
|
| 191 |
+
def name(self, tag):
|
| 192 |
+
"""
|
| 193 |
+
Convert a BCP-47 tag to a colon-separated string of subtag names
|
| 194 |
+
|
| 195 |
+
>>> from nltk.corpus import bcp47
|
| 196 |
+
>>> bcp47.name('ca-Latn-ES-valencia')
|
| 197 |
+
'Catalan: Latin: Spain: Valencian'
|
| 198 |
+
|
| 199 |
+
"""
|
| 200 |
+
for label in ["redundant", "grandfathered"]:
|
| 201 |
+
val = None
|
| 202 |
+
if tag in self.db[label]:
|
| 203 |
+
val = f"{self.db[label][tag]['Description']}"
|
| 204 |
+
note = f"The {tag!r} code is {label}"
|
| 205 |
+
elif tag in self.db["deprecated"][label]:
|
| 206 |
+
val = f"{self.db['deprecated'][label][tag]['Description']}"
|
| 207 |
+
note = f"The {tag!r} code is {label} and deprecated"
|
| 208 |
+
if "Preferred-Value" in self.db["deprecated"][label][tag]:
|
| 209 |
+
prefer = self.db["deprecated"][label][tag]["Preferred-Value"]
|
| 210 |
+
note += f", prefer {self.val2str(prefer)!r}"
|
| 211 |
+
if val:
|
| 212 |
+
warn(note)
|
| 213 |
+
return val
|
| 214 |
+
try:
|
| 215 |
+
return self.lang2str(self.parse_tag(tag))
|
| 216 |
+
except:
|
| 217 |
+
warn(f"Tag {tag!r} was not recognized")
|
| 218 |
+
return None
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bnc.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Plaintext Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Edward Loper <edloper@gmail.com>
|
| 5 |
+
# URL: <https://www.nltk.org/>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
"""Corpus reader for the XML version of the British National Corpus."""
|
| 9 |
+
|
| 10 |
+
from nltk.corpus.reader.util import concat
|
| 11 |
+
from nltk.corpus.reader.xmldocs import ElementTree, XMLCorpusReader, XMLCorpusView
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class BNCCorpusReader(XMLCorpusReader):
|
| 15 |
+
r"""Corpus reader for the XML version of the British National Corpus.
|
| 16 |
+
|
| 17 |
+
For access to the complete XML data structure, use the ``xml()``
|
| 18 |
+
method. For access to simple word lists and tagged word lists, use
|
| 19 |
+
``words()``, ``sents()``, ``tagged_words()``, and ``tagged_sents()``.
|
| 20 |
+
|
| 21 |
+
You can obtain the full version of the BNC corpus at
|
| 22 |
+
https://www.ota.ox.ac.uk/desc/2554
|
| 23 |
+
|
| 24 |
+
If you extracted the archive to a directory called `BNC`, then you can
|
| 25 |
+
instantiate the reader as::
|
| 26 |
+
|
| 27 |
+
BNCCorpusReader(root='BNC/Texts/', fileids=r'[A-K]/\w*/\w*\.xml')
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, root, fileids, lazy=True):
|
| 32 |
+
XMLCorpusReader.__init__(self, root, fileids)
|
| 33 |
+
self._lazy = lazy
|
| 34 |
+
|
| 35 |
+
def words(self, fileids=None, strip_space=True, stem=False):
|
| 36 |
+
"""
|
| 37 |
+
:return: the given file(s) as a list of words
|
| 38 |
+
and punctuation symbols.
|
| 39 |
+
:rtype: list(str)
|
| 40 |
+
|
| 41 |
+
:param strip_space: If true, then strip trailing spaces from
|
| 42 |
+
word tokens. Otherwise, leave the spaces on the tokens.
|
| 43 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 44 |
+
"""
|
| 45 |
+
return self._views(fileids, False, None, strip_space, stem)
|
| 46 |
+
|
| 47 |
+
def tagged_words(self, fileids=None, c5=False, strip_space=True, stem=False):
|
| 48 |
+
"""
|
| 49 |
+
:return: the given file(s) as a list of tagged
|
| 50 |
+
words and punctuation symbols, encoded as tuples
|
| 51 |
+
``(word,tag)``.
|
| 52 |
+
:rtype: list(tuple(str,str))
|
| 53 |
+
|
| 54 |
+
:param c5: If true, then the tags used will be the more detailed
|
| 55 |
+
c5 tags. Otherwise, the simplified tags will be used.
|
| 56 |
+
:param strip_space: If true, then strip trailing spaces from
|
| 57 |
+
word tokens. Otherwise, leave the spaces on the tokens.
|
| 58 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 59 |
+
"""
|
| 60 |
+
tag = "c5" if c5 else "pos"
|
| 61 |
+
return self._views(fileids, False, tag, strip_space, stem)
|
| 62 |
+
|
| 63 |
+
def sents(self, fileids=None, strip_space=True, stem=False):
|
| 64 |
+
"""
|
| 65 |
+
:return: the given file(s) as a list of
|
| 66 |
+
sentences or utterances, each encoded as a list of word
|
| 67 |
+
strings.
|
| 68 |
+
:rtype: list(list(str))
|
| 69 |
+
|
| 70 |
+
:param strip_space: If true, then strip trailing spaces from
|
| 71 |
+
word tokens. Otherwise, leave the spaces on the tokens.
|
| 72 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 73 |
+
"""
|
| 74 |
+
return self._views(fileids, True, None, strip_space, stem)
|
| 75 |
+
|
| 76 |
+
def tagged_sents(self, fileids=None, c5=False, strip_space=True, stem=False):
|
| 77 |
+
"""
|
| 78 |
+
:return: the given file(s) as a list of
|
| 79 |
+
sentences, each encoded as a list of ``(word,tag)`` tuples.
|
| 80 |
+
:rtype: list(list(tuple(str,str)))
|
| 81 |
+
|
| 82 |
+
:param c5: If true, then the tags used will be the more detailed
|
| 83 |
+
c5 tags. Otherwise, the simplified tags will be used.
|
| 84 |
+
:param strip_space: If true, then strip trailing spaces from
|
| 85 |
+
word tokens. Otherwise, leave the spaces on the tokens.
|
| 86 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 87 |
+
"""
|
| 88 |
+
tag = "c5" if c5 else "pos"
|
| 89 |
+
return self._views(
|
| 90 |
+
fileids, sent=True, tag=tag, strip_space=strip_space, stem=stem
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def _views(self, fileids=None, sent=False, tag=False, strip_space=True, stem=False):
|
| 94 |
+
"""A helper function that instantiates BNCWordViews or the list of words/sentences."""
|
| 95 |
+
f = BNCWordView if self._lazy else self._words
|
| 96 |
+
return concat(
|
| 97 |
+
[
|
| 98 |
+
f(fileid, sent, tag, strip_space, stem)
|
| 99 |
+
for fileid in self.abspaths(fileids)
|
| 100 |
+
]
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def _words(self, fileid, bracket_sent, tag, strip_space, stem):
|
| 104 |
+
"""
|
| 105 |
+
Helper used to implement the view methods -- returns a list of
|
| 106 |
+
words or a list of sentences, optionally tagged.
|
| 107 |
+
|
| 108 |
+
:param fileid: The name of the underlying file.
|
| 109 |
+
:param bracket_sent: If true, include sentence bracketing.
|
| 110 |
+
:param tag: The name of the tagset to use, or None for no tags.
|
| 111 |
+
:param strip_space: If true, strip spaces from word tokens.
|
| 112 |
+
:param stem: If true, then substitute stems for words.
|
| 113 |
+
"""
|
| 114 |
+
result = []
|
| 115 |
+
|
| 116 |
+
xmldoc = ElementTree.parse(fileid).getroot()
|
| 117 |
+
for xmlsent in xmldoc.findall(".//s"):
|
| 118 |
+
sent = []
|
| 119 |
+
for xmlword in _all_xmlwords_in(xmlsent):
|
| 120 |
+
word = xmlword.text
|
| 121 |
+
if not word:
|
| 122 |
+
word = "" # fixes issue 337?
|
| 123 |
+
if strip_space or stem:
|
| 124 |
+
word = word.strip()
|
| 125 |
+
if stem:
|
| 126 |
+
word = xmlword.get("hw", word)
|
| 127 |
+
if tag == "c5":
|
| 128 |
+
word = (word, xmlword.get("c5"))
|
| 129 |
+
elif tag == "pos":
|
| 130 |
+
word = (word, xmlword.get("pos", xmlword.get("c5")))
|
| 131 |
+
sent.append(word)
|
| 132 |
+
if bracket_sent:
|
| 133 |
+
result.append(BNCSentence(xmlsent.attrib["n"], sent))
|
| 134 |
+
else:
|
| 135 |
+
result.extend(sent)
|
| 136 |
+
|
| 137 |
+
assert None not in result
|
| 138 |
+
return result
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _all_xmlwords_in(elt, result=None):
|
| 142 |
+
if result is None:
|
| 143 |
+
result = []
|
| 144 |
+
for child in elt:
|
| 145 |
+
if child.tag in ("c", "w"):
|
| 146 |
+
result.append(child)
|
| 147 |
+
else:
|
| 148 |
+
_all_xmlwords_in(child, result)
|
| 149 |
+
return result
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class BNCSentence(list):
|
| 153 |
+
"""
|
| 154 |
+
A list of words, augmented by an attribute ``num`` used to record
|
| 155 |
+
the sentence identifier (the ``n`` attribute from the XML).
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
def __init__(self, num, items):
|
| 159 |
+
self.num = num
|
| 160 |
+
list.__init__(self, items)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class BNCWordView(XMLCorpusView):
|
| 164 |
+
"""
|
| 165 |
+
A stream backed corpus view specialized for use with the BNC corpus.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
tags_to_ignore = {
|
| 169 |
+
"pb",
|
| 170 |
+
"gap",
|
| 171 |
+
"vocal",
|
| 172 |
+
"event",
|
| 173 |
+
"unclear",
|
| 174 |
+
"shift",
|
| 175 |
+
"pause",
|
| 176 |
+
"align",
|
| 177 |
+
}
|
| 178 |
+
"""These tags are ignored. For their description refer to the
|
| 179 |
+
technical documentation, for example,
|
| 180 |
+
http://www.natcorp.ox.ac.uk/docs/URG/ref-vocal.html
|
| 181 |
+
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
def __init__(self, fileid, sent, tag, strip_space, stem):
|
| 185 |
+
"""
|
| 186 |
+
:param fileid: The name of the underlying file.
|
| 187 |
+
:param sent: If true, include sentence bracketing.
|
| 188 |
+
:param tag: The name of the tagset to use, or None for no tags.
|
| 189 |
+
:param strip_space: If true, strip spaces from word tokens.
|
| 190 |
+
:param stem: If true, then substitute stems for words.
|
| 191 |
+
"""
|
| 192 |
+
if sent:
|
| 193 |
+
tagspec = ".*/s"
|
| 194 |
+
else:
|
| 195 |
+
tagspec = ".*/s/(.*/)?(c|w)"
|
| 196 |
+
self._sent = sent
|
| 197 |
+
self._tag = tag
|
| 198 |
+
self._strip_space = strip_space
|
| 199 |
+
self._stem = stem
|
| 200 |
+
|
| 201 |
+
self.title = None #: Title of the document.
|
| 202 |
+
self.author = None #: Author of the document.
|
| 203 |
+
self.editor = None #: Editor
|
| 204 |
+
self.resps = None #: Statement of responsibility
|
| 205 |
+
|
| 206 |
+
XMLCorpusView.__init__(self, fileid, tagspec)
|
| 207 |
+
|
| 208 |
+
# Read in a tasty header.
|
| 209 |
+
self._open()
|
| 210 |
+
self.read_block(self._stream, ".*/teiHeader$", self.handle_header)
|
| 211 |
+
self.close()
|
| 212 |
+
|
| 213 |
+
# Reset tag context.
|
| 214 |
+
self._tag_context = {0: ()}
|
| 215 |
+
|
| 216 |
+
def handle_header(self, elt, context):
|
| 217 |
+
# Set up some metadata!
|
| 218 |
+
titles = elt.findall("titleStmt/title")
|
| 219 |
+
if titles:
|
| 220 |
+
self.title = "\n".join(title.text.strip() for title in titles)
|
| 221 |
+
|
| 222 |
+
authors = elt.findall("titleStmt/author")
|
| 223 |
+
if authors:
|
| 224 |
+
self.author = "\n".join(author.text.strip() for author in authors)
|
| 225 |
+
|
| 226 |
+
editors = elt.findall("titleStmt/editor")
|
| 227 |
+
if editors:
|
| 228 |
+
self.editor = "\n".join(editor.text.strip() for editor in editors)
|
| 229 |
+
|
| 230 |
+
resps = elt.findall("titleStmt/respStmt")
|
| 231 |
+
if resps:
|
| 232 |
+
self.resps = "\n\n".join(
|
| 233 |
+
"\n".join(resp_elt.text.strip() for resp_elt in resp) for resp in resps
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def handle_elt(self, elt, context):
|
| 237 |
+
if self._sent:
|
| 238 |
+
return self.handle_sent(elt)
|
| 239 |
+
else:
|
| 240 |
+
return self.handle_word(elt)
|
| 241 |
+
|
| 242 |
+
def handle_word(self, elt):
|
| 243 |
+
word = elt.text
|
| 244 |
+
if not word:
|
| 245 |
+
word = "" # fixes issue 337?
|
| 246 |
+
if self._strip_space or self._stem:
|
| 247 |
+
word = word.strip()
|
| 248 |
+
if self._stem:
|
| 249 |
+
word = elt.get("hw", word)
|
| 250 |
+
if self._tag == "c5":
|
| 251 |
+
word = (word, elt.get("c5"))
|
| 252 |
+
elif self._tag == "pos":
|
| 253 |
+
word = (word, elt.get("pos", elt.get("c5")))
|
| 254 |
+
return word
|
| 255 |
+
|
| 256 |
+
def handle_sent(self, elt):
|
| 257 |
+
sent = []
|
| 258 |
+
for child in elt:
|
| 259 |
+
if child.tag in ("mw", "hi", "corr", "trunc"):
|
| 260 |
+
sent += [self.handle_word(w) for w in child]
|
| 261 |
+
elif child.tag in ("w", "c"):
|
| 262 |
+
sent.append(self.handle_word(child))
|
| 263 |
+
elif child.tag not in self.tags_to_ignore:
|
| 264 |
+
raise ValueError("Unexpected element %s" % child.tag)
|
| 265 |
+
return BNCSentence(elt.attrib["n"], sent)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/bracket_parse.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Penn Treebank Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 5 |
+
# Edward Loper <edloper@gmail.com>
|
| 6 |
+
# URL: <https://www.nltk.org/>
|
| 7 |
+
# For license information, see LICENSE.TXT
|
| 8 |
+
"""
|
| 9 |
+
Corpus reader for corpora that consist of parenthesis-delineated parse trees.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
|
| 14 |
+
from nltk.corpus.reader.api import *
|
| 15 |
+
from nltk.corpus.reader.util import *
|
| 16 |
+
from nltk.tag import map_tag
|
| 17 |
+
from nltk.tree import Tree
|
| 18 |
+
|
| 19 |
+
# we use [^\s()]+ instead of \S+? to avoid matching ()
|
| 20 |
+
SORTTAGWRD = re.compile(r"\((\d+) ([^\s()]+) ([^\s()]+)\)")
|
| 21 |
+
TAGWORD = re.compile(r"\(([^\s()]+) ([^\s()]+)\)")
|
| 22 |
+
WORD = re.compile(r"\([^\s()]+ ([^\s()]+)\)")
|
| 23 |
+
EMPTY_BRACKETS = re.compile(r"\s*\(\s*\(")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class BracketParseCorpusReader(SyntaxCorpusReader):
|
| 27 |
+
"""
|
| 28 |
+
Reader for corpora that consist of parenthesis-delineated parse trees,
|
| 29 |
+
like those found in the "combined" section of the Penn Treebank,
|
| 30 |
+
e.g. "(S (NP (DT the) (JJ little) (NN dog)) (VP (VBD barked)))".
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
root,
|
| 37 |
+
fileids,
|
| 38 |
+
comment_char=None,
|
| 39 |
+
detect_blocks="unindented_paren",
|
| 40 |
+
encoding="utf8",
|
| 41 |
+
tagset=None,
|
| 42 |
+
):
|
| 43 |
+
"""
|
| 44 |
+
:param root: The root directory for this corpus.
|
| 45 |
+
:param fileids: A list or regexp specifying the fileids in this corpus.
|
| 46 |
+
:param comment_char: The character which can appear at the start of
|
| 47 |
+
a line to indicate that the rest of the line is a comment.
|
| 48 |
+
:param detect_blocks: The method that is used to find blocks
|
| 49 |
+
in the corpus; can be 'unindented_paren' (every unindented
|
| 50 |
+
parenthesis starts a new parse) or 'sexpr' (brackets are
|
| 51 |
+
matched).
|
| 52 |
+
:param tagset: The name of the tagset used by this corpus, to be used
|
| 53 |
+
for normalizing or converting the POS tags returned by the
|
| 54 |
+
``tagged_...()`` methods.
|
| 55 |
+
"""
|
| 56 |
+
SyntaxCorpusReader.__init__(self, root, fileids, encoding)
|
| 57 |
+
self._comment_char = comment_char
|
| 58 |
+
self._detect_blocks = detect_blocks
|
| 59 |
+
self._tagset = tagset
|
| 60 |
+
|
| 61 |
+
def _read_block(self, stream):
|
| 62 |
+
if self._detect_blocks == "sexpr":
|
| 63 |
+
return read_sexpr_block(stream, comment_char=self._comment_char)
|
| 64 |
+
elif self._detect_blocks == "blankline":
|
| 65 |
+
return read_blankline_block(stream)
|
| 66 |
+
elif self._detect_blocks == "unindented_paren":
|
| 67 |
+
# Tokens start with unindented left parens.
|
| 68 |
+
toks = read_regexp_block(stream, start_re=r"^\(")
|
| 69 |
+
# Strip any comments out of the tokens.
|
| 70 |
+
if self._comment_char:
|
| 71 |
+
toks = [
|
| 72 |
+
re.sub("(?m)^%s.*" % re.escape(self._comment_char), "", tok)
|
| 73 |
+
for tok in toks
|
| 74 |
+
]
|
| 75 |
+
return toks
|
| 76 |
+
else:
|
| 77 |
+
assert 0, "bad block type"
|
| 78 |
+
|
| 79 |
+
def _normalize(self, t):
|
| 80 |
+
# Replace leaves of the form (!), (,), with (! !), (, ,)
|
| 81 |
+
t = re.sub(r"\((.)\)", r"(\1 \1)", t)
|
| 82 |
+
# Replace leaves of the form (tag word root) with (tag word)
|
| 83 |
+
t = re.sub(r"\(([^\s()]+) ([^\s()]+) [^\s()]+\)", r"(\1 \2)", t)
|
| 84 |
+
return t
|
| 85 |
+
|
| 86 |
+
def _parse(self, t):
|
| 87 |
+
try:
|
| 88 |
+
tree = Tree.fromstring(self._normalize(t))
|
| 89 |
+
# If there's an empty node at the top, strip it off
|
| 90 |
+
if tree.label() == "" and len(tree) == 1:
|
| 91 |
+
return tree[0]
|
| 92 |
+
else:
|
| 93 |
+
return tree
|
| 94 |
+
|
| 95 |
+
except ValueError as e:
|
| 96 |
+
sys.stderr.write("Bad tree detected; trying to recover...\n")
|
| 97 |
+
# Try to recover, if we can:
|
| 98 |
+
if e.args == ("mismatched parens",):
|
| 99 |
+
for n in range(1, 5):
|
| 100 |
+
try:
|
| 101 |
+
v = Tree(self._normalize(t + ")" * n))
|
| 102 |
+
sys.stderr.write(
|
| 103 |
+
" Recovered by adding %d close " "paren(s)\n" % n
|
| 104 |
+
)
|
| 105 |
+
return v
|
| 106 |
+
except ValueError:
|
| 107 |
+
pass
|
| 108 |
+
# Try something else:
|
| 109 |
+
sys.stderr.write(" Recovered by returning a flat parse.\n")
|
| 110 |
+
# sys.stderr.write(' '.join(t.split())+'\n')
|
| 111 |
+
return Tree("S", self._tag(t))
|
| 112 |
+
|
| 113 |
+
def _tag(self, t, tagset=None):
|
| 114 |
+
tagged_sent = [(w, p) for (p, w) in TAGWORD.findall(self._normalize(t))]
|
| 115 |
+
if tagset and tagset != self._tagset:
|
| 116 |
+
tagged_sent = [
|
| 117 |
+
(w, map_tag(self._tagset, tagset, p)) for (w, p) in tagged_sent
|
| 118 |
+
]
|
| 119 |
+
return tagged_sent
|
| 120 |
+
|
| 121 |
+
def _word(self, t):
|
| 122 |
+
return WORD.findall(self._normalize(t))
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class CategorizedBracketParseCorpusReader(
|
| 126 |
+
CategorizedCorpusReader, BracketParseCorpusReader
|
| 127 |
+
):
|
| 128 |
+
"""
|
| 129 |
+
A reader for parsed corpora whose documents are
|
| 130 |
+
divided into categories based on their file identifiers.
|
| 131 |
+
@author: Nathan Schneider <nschneid@cs.cmu.edu>
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def __init__(self, *args, **kwargs):
|
| 135 |
+
"""
|
| 136 |
+
Initialize the corpus reader. Categorization arguments
|
| 137 |
+
(C{cat_pattern}, C{cat_map}, and C{cat_file}) are passed to
|
| 138 |
+
the L{CategorizedCorpusReader constructor
|
| 139 |
+
<CategorizedCorpusReader.__init__>}. The remaining arguments
|
| 140 |
+
are passed to the L{BracketParseCorpusReader constructor
|
| 141 |
+
<BracketParseCorpusReader.__init__>}.
|
| 142 |
+
"""
|
| 143 |
+
CategorizedCorpusReader.__init__(self, kwargs)
|
| 144 |
+
BracketParseCorpusReader.__init__(self, *args, **kwargs)
|
| 145 |
+
|
| 146 |
+
def tagged_words(self, fileids=None, categories=None, tagset=None):
|
| 147 |
+
return super().tagged_words(self._resolve(fileids, categories), tagset)
|
| 148 |
+
|
| 149 |
+
def tagged_sents(self, fileids=None, categories=None, tagset=None):
|
| 150 |
+
return super().tagged_sents(self._resolve(fileids, categories), tagset)
|
| 151 |
+
|
| 152 |
+
def tagged_paras(self, fileids=None, categories=None, tagset=None):
|
| 153 |
+
return super().tagged_paras(self._resolve(fileids, categories), tagset)
|
| 154 |
+
|
| 155 |
+
def parsed_words(self, fileids=None, categories=None):
|
| 156 |
+
return super().parsed_words(self._resolve(fileids, categories))
|
| 157 |
+
|
| 158 |
+
def parsed_sents(self, fileids=None, categories=None):
|
| 159 |
+
return super().parsed_sents(self._resolve(fileids, categories))
|
| 160 |
+
|
| 161 |
+
def parsed_paras(self, fileids=None, categories=None):
|
| 162 |
+
return super().parsed_paras(self._resolve(fileids, categories))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class AlpinoCorpusReader(BracketParseCorpusReader):
|
| 166 |
+
"""
|
| 167 |
+
Reader for the Alpino Dutch Treebank.
|
| 168 |
+
This corpus has a lexical breakdown structure embedded, as read by `_parse`
|
| 169 |
+
Unfortunately this puts punctuation and some other words out of the sentence
|
| 170 |
+
order in the xml element tree. This is no good for `tag_` and `word_`
|
| 171 |
+
`_tag` and `_word` will be overridden to use a non-default new parameter 'ordered'
|
| 172 |
+
to the overridden _normalize function. The _parse function can then remain
|
| 173 |
+
untouched.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, root, encoding="ISO-8859-1", tagset=None):
|
| 177 |
+
BracketParseCorpusReader.__init__(
|
| 178 |
+
self,
|
| 179 |
+
root,
|
| 180 |
+
r"alpino\.xml",
|
| 181 |
+
detect_blocks="blankline",
|
| 182 |
+
encoding=encoding,
|
| 183 |
+
tagset=tagset,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
def _normalize(self, t, ordered=False):
|
| 187 |
+
"""Normalize the xml sentence element in t.
|
| 188 |
+
The sentence elements <alpino_ds>, although embedded in a few overall
|
| 189 |
+
xml elements, are separated by blank lines. That's how the reader can
|
| 190 |
+
deliver them one at a time.
|
| 191 |
+
Each sentence has a few category subnodes that are of no use to us.
|
| 192 |
+
The remaining word nodes may or may not appear in the proper order.
|
| 193 |
+
Each word node has attributes, among which:
|
| 194 |
+
- begin : the position of the word in the sentence
|
| 195 |
+
- pos : Part of Speech: the Tag
|
| 196 |
+
- word : the actual word
|
| 197 |
+
The return value is a string with all xml elementes replaced by
|
| 198 |
+
clauses: either a cat clause with nested clauses, or a word clause.
|
| 199 |
+
The order of the bracket clauses closely follows the xml.
|
| 200 |
+
If ordered == True, the word clauses include an order sequence number.
|
| 201 |
+
If ordered == False, the word clauses only have pos and word parts.
|
| 202 |
+
"""
|
| 203 |
+
if t[:10] != "<alpino_ds":
|
| 204 |
+
return ""
|
| 205 |
+
# convert XML to sexpr notation
|
| 206 |
+
t = re.sub(r' <node .*? cat="(\w+)".*>', r"(\1", t)
|
| 207 |
+
if ordered:
|
| 208 |
+
t = re.sub(
|
| 209 |
+
r' <node. *?begin="(\d+)".*? pos="(\w+)".*? word="([^"]+)".*?/>',
|
| 210 |
+
r"(\1 \2 \3)",
|
| 211 |
+
t,
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
t = re.sub(r' <node .*?pos="(\w+)".*? word="([^"]+)".*?/>', r"(\1 \2)", t)
|
| 215 |
+
t = re.sub(r" </node>", r")", t)
|
| 216 |
+
t = re.sub(r"<sentence>.*</sentence>", r"", t)
|
| 217 |
+
t = re.sub(r"</?alpino_ds.*>", r"", t)
|
| 218 |
+
return t
|
| 219 |
+
|
| 220 |
+
def _tag(self, t, tagset=None):
|
| 221 |
+
tagged_sent = [
|
| 222 |
+
(int(o), w, p)
|
| 223 |
+
for (o, p, w) in SORTTAGWRD.findall(self._normalize(t, ordered=True))
|
| 224 |
+
]
|
| 225 |
+
tagged_sent.sort()
|
| 226 |
+
if tagset and tagset != self._tagset:
|
| 227 |
+
tagged_sent = [
|
| 228 |
+
(w, map_tag(self._tagset, tagset, p)) for (o, w, p) in tagged_sent
|
| 229 |
+
]
|
| 230 |
+
else:
|
| 231 |
+
tagged_sent = [(w, p) for (o, w, p) in tagged_sent]
|
| 232 |
+
return tagged_sent
|
| 233 |
+
|
| 234 |
+
def _word(self, t):
|
| 235 |
+
"""Return a correctly ordered list if words"""
|
| 236 |
+
tagged_sent = self._tag(t)
|
| 237 |
+
return [w for (w, p) in tagged_sent]
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/categorized_sents.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Categorized Sentences Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Pierpaolo Pantone <24alsecondo@gmail.com>
|
| 5 |
+
# URL: <https://www.nltk.org/>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
CorpusReader structured for corpora that contain one instance on each row.
|
| 10 |
+
This CorpusReader is specifically used for the Subjectivity Dataset and the
|
| 11 |
+
Sentence Polarity Dataset.
|
| 12 |
+
|
| 13 |
+
- Subjectivity Dataset information -
|
| 14 |
+
|
| 15 |
+
Authors: Bo Pang and Lillian Lee.
|
| 16 |
+
Url: https://www.cs.cornell.edu/people/pabo/movie-review-data
|
| 17 |
+
|
| 18 |
+
Distributed with permission.
|
| 19 |
+
|
| 20 |
+
Related papers:
|
| 21 |
+
|
| 22 |
+
- Bo Pang and Lillian Lee. "A Sentimental Education: Sentiment Analysis Using
|
| 23 |
+
Subjectivity Summarization Based on Minimum Cuts". Proceedings of the ACL,
|
| 24 |
+
2004.
|
| 25 |
+
|
| 26 |
+
- Sentence Polarity Dataset information -
|
| 27 |
+
|
| 28 |
+
Authors: Bo Pang and Lillian Lee.
|
| 29 |
+
Url: https://www.cs.cornell.edu/people/pabo/movie-review-data
|
| 30 |
+
|
| 31 |
+
Related papers:
|
| 32 |
+
|
| 33 |
+
- Bo Pang and Lillian Lee. "Seeing stars: Exploiting class relationships for
|
| 34 |
+
sentiment categorization with respect to rating scales". Proceedings of the
|
| 35 |
+
ACL, 2005.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from nltk.corpus.reader.api import *
|
| 39 |
+
from nltk.tokenize import *
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class CategorizedSentencesCorpusReader(CategorizedCorpusReader, CorpusReader):
|
| 43 |
+
"""
|
| 44 |
+
A reader for corpora in which each row represents a single instance, mainly
|
| 45 |
+
a sentence. Istances are divided into categories based on their file identifiers
|
| 46 |
+
(see CategorizedCorpusReader).
|
| 47 |
+
Since many corpora allow rows that contain more than one sentence, it is
|
| 48 |
+
possible to specify a sentence tokenizer to retrieve all sentences instead
|
| 49 |
+
than all rows.
|
| 50 |
+
|
| 51 |
+
Examples using the Subjectivity Dataset:
|
| 52 |
+
|
| 53 |
+
>>> from nltk.corpus import subjectivity
|
| 54 |
+
>>> subjectivity.sents()[23] # doctest: +NORMALIZE_WHITESPACE
|
| 55 |
+
['television', 'made', 'him', 'famous', ',', 'but', 'his', 'biggest', 'hits',
|
| 56 |
+
'happened', 'off', 'screen', '.']
|
| 57 |
+
>>> subjectivity.categories()
|
| 58 |
+
['obj', 'subj']
|
| 59 |
+
>>> subjectivity.words(categories='subj')
|
| 60 |
+
['smart', 'and', 'alert', ',', 'thirteen', ...]
|
| 61 |
+
|
| 62 |
+
Examples using the Sentence Polarity Dataset:
|
| 63 |
+
|
| 64 |
+
>>> from nltk.corpus import sentence_polarity
|
| 65 |
+
>>> sentence_polarity.sents() # doctest: +NORMALIZE_WHITESPACE
|
| 66 |
+
[['simplistic', ',', 'silly', 'and', 'tedious', '.'], ["it's", 'so', 'laddish',
|
| 67 |
+
'and', 'juvenile', ',', 'only', 'teenage', 'boys', 'could', 'possibly', 'find',
|
| 68 |
+
'it', 'funny', '.'], ...]
|
| 69 |
+
>>> sentence_polarity.categories()
|
| 70 |
+
['neg', 'pos']
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
CorpusView = StreamBackedCorpusView
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self,
|
| 77 |
+
root,
|
| 78 |
+
fileids,
|
| 79 |
+
word_tokenizer=WhitespaceTokenizer(),
|
| 80 |
+
sent_tokenizer=None,
|
| 81 |
+
encoding="utf8",
|
| 82 |
+
**kwargs
|
| 83 |
+
):
|
| 84 |
+
"""
|
| 85 |
+
:param root: The root directory for the corpus.
|
| 86 |
+
:param fileids: a list or regexp specifying the fileids in the corpus.
|
| 87 |
+
:param word_tokenizer: a tokenizer for breaking sentences or paragraphs
|
| 88 |
+
into words. Default: `WhitespaceTokenizer`
|
| 89 |
+
:param sent_tokenizer: a tokenizer for breaking paragraphs into sentences.
|
| 90 |
+
:param encoding: the encoding that should be used to read the corpus.
|
| 91 |
+
:param kwargs: additional parameters passed to CategorizedCorpusReader.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
CorpusReader.__init__(self, root, fileids, encoding)
|
| 95 |
+
CategorizedCorpusReader.__init__(self, kwargs)
|
| 96 |
+
self._word_tokenizer = word_tokenizer
|
| 97 |
+
self._sent_tokenizer = sent_tokenizer
|
| 98 |
+
|
| 99 |
+
def sents(self, fileids=None, categories=None):
|
| 100 |
+
"""
|
| 101 |
+
Return all sentences in the corpus or in the specified file(s).
|
| 102 |
+
|
| 103 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 104 |
+
sentences have to be returned.
|
| 105 |
+
:param categories: a list specifying the categories whose sentences have
|
| 106 |
+
to be returned.
|
| 107 |
+
:return: the given file(s) as a list of sentences.
|
| 108 |
+
Each sentence is tokenized using the specified word_tokenizer.
|
| 109 |
+
:rtype: list(list(str))
|
| 110 |
+
"""
|
| 111 |
+
fileids = self._resolve(fileids, categories)
|
| 112 |
+
if fileids is None:
|
| 113 |
+
fileids = self._fileids
|
| 114 |
+
elif isinstance(fileids, str):
|
| 115 |
+
fileids = [fileids]
|
| 116 |
+
return concat(
|
| 117 |
+
[
|
| 118 |
+
self.CorpusView(path, self._read_sent_block, encoding=enc)
|
| 119 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 120 |
+
]
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def words(self, fileids=None, categories=None):
|
| 124 |
+
"""
|
| 125 |
+
Return all words and punctuation symbols in the corpus or in the specified
|
| 126 |
+
file(s).
|
| 127 |
+
|
| 128 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 129 |
+
words have to be returned.
|
| 130 |
+
:param categories: a list specifying the categories whose words have to
|
| 131 |
+
be returned.
|
| 132 |
+
:return: the given file(s) as a list of words and punctuation symbols.
|
| 133 |
+
:rtype: list(str)
|
| 134 |
+
"""
|
| 135 |
+
fileids = self._resolve(fileids, categories)
|
| 136 |
+
if fileids is None:
|
| 137 |
+
fileids = self._fileids
|
| 138 |
+
elif isinstance(fileids, str):
|
| 139 |
+
fileids = [fileids]
|
| 140 |
+
return concat(
|
| 141 |
+
[
|
| 142 |
+
self.CorpusView(path, self._read_word_block, encoding=enc)
|
| 143 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 144 |
+
]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def _read_sent_block(self, stream):
|
| 148 |
+
sents = []
|
| 149 |
+
for i in range(20): # Read 20 lines at a time.
|
| 150 |
+
line = stream.readline()
|
| 151 |
+
if not line:
|
| 152 |
+
continue
|
| 153 |
+
if self._sent_tokenizer:
|
| 154 |
+
sents.extend(
|
| 155 |
+
[
|
| 156 |
+
self._word_tokenizer.tokenize(sent)
|
| 157 |
+
for sent in self._sent_tokenizer.tokenize(line)
|
| 158 |
+
]
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
sents.append(self._word_tokenizer.tokenize(line))
|
| 162 |
+
return sents
|
| 163 |
+
|
| 164 |
+
def _read_word_block(self, stream):
|
| 165 |
+
words = []
|
| 166 |
+
for sent in self._read_sent_block(stream):
|
| 167 |
+
words.extend(sent)
|
| 168 |
+
return words
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/chasen.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 3 |
+
# Author: Masato Hagiwara <hagisan@gmail.com>
|
| 4 |
+
# URL: <https://www.nltk.org/>
|
| 5 |
+
# For license information, see LICENSE.TXT
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
from nltk.corpus.reader import util
|
| 10 |
+
from nltk.corpus.reader.api import *
|
| 11 |
+
from nltk.corpus.reader.util import *
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ChasenCorpusReader(CorpusReader):
|
| 15 |
+
def __init__(self, root, fileids, encoding="utf8", sent_splitter=None):
|
| 16 |
+
self._sent_splitter = sent_splitter
|
| 17 |
+
CorpusReader.__init__(self, root, fileids, encoding)
|
| 18 |
+
|
| 19 |
+
def words(self, fileids=None):
|
| 20 |
+
return concat(
|
| 21 |
+
[
|
| 22 |
+
ChasenCorpusView(fileid, enc, False, False, False, self._sent_splitter)
|
| 23 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 24 |
+
]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def tagged_words(self, fileids=None):
|
| 28 |
+
return concat(
|
| 29 |
+
[
|
| 30 |
+
ChasenCorpusView(fileid, enc, True, False, False, self._sent_splitter)
|
| 31 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 32 |
+
]
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def sents(self, fileids=None):
|
| 36 |
+
return concat(
|
| 37 |
+
[
|
| 38 |
+
ChasenCorpusView(fileid, enc, False, True, False, self._sent_splitter)
|
| 39 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
def tagged_sents(self, fileids=None):
|
| 44 |
+
return concat(
|
| 45 |
+
[
|
| 46 |
+
ChasenCorpusView(fileid, enc, True, True, False, self._sent_splitter)
|
| 47 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 48 |
+
]
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def paras(self, fileids=None):
|
| 52 |
+
return concat(
|
| 53 |
+
[
|
| 54 |
+
ChasenCorpusView(fileid, enc, False, True, True, self._sent_splitter)
|
| 55 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 56 |
+
]
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def tagged_paras(self, fileids=None):
|
| 60 |
+
return concat(
|
| 61 |
+
[
|
| 62 |
+
ChasenCorpusView(fileid, enc, True, True, True, self._sent_splitter)
|
| 63 |
+
for (fileid, enc) in self.abspaths(fileids, True)
|
| 64 |
+
]
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class ChasenCorpusView(StreamBackedCorpusView):
|
| 69 |
+
"""
|
| 70 |
+
A specialized corpus view for ChasenReader. Similar to ``TaggedCorpusView``,
|
| 71 |
+
but this'll use fixed sets of word and sentence tokenizer.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(
|
| 75 |
+
self,
|
| 76 |
+
corpus_file,
|
| 77 |
+
encoding,
|
| 78 |
+
tagged,
|
| 79 |
+
group_by_sent,
|
| 80 |
+
group_by_para,
|
| 81 |
+
sent_splitter=None,
|
| 82 |
+
):
|
| 83 |
+
self._tagged = tagged
|
| 84 |
+
self._group_by_sent = group_by_sent
|
| 85 |
+
self._group_by_para = group_by_para
|
| 86 |
+
self._sent_splitter = sent_splitter
|
| 87 |
+
StreamBackedCorpusView.__init__(self, corpus_file, encoding=encoding)
|
| 88 |
+
|
| 89 |
+
def read_block(self, stream):
|
| 90 |
+
"""Reads one paragraph at a time."""
|
| 91 |
+
block = []
|
| 92 |
+
for para_str in read_regexp_block(stream, r".", r"^EOS\n"):
|
| 93 |
+
|
| 94 |
+
para = []
|
| 95 |
+
|
| 96 |
+
sent = []
|
| 97 |
+
for line in para_str.splitlines():
|
| 98 |
+
|
| 99 |
+
_eos = line.strip() == "EOS"
|
| 100 |
+
_cells = line.split("\t")
|
| 101 |
+
w = (_cells[0], "\t".join(_cells[1:]))
|
| 102 |
+
if not _eos:
|
| 103 |
+
sent.append(w)
|
| 104 |
+
|
| 105 |
+
if _eos or (self._sent_splitter and self._sent_splitter(w)):
|
| 106 |
+
if not self._tagged:
|
| 107 |
+
sent = [w for (w, t) in sent]
|
| 108 |
+
if self._group_by_sent:
|
| 109 |
+
para.append(sent)
|
| 110 |
+
else:
|
| 111 |
+
para.extend(sent)
|
| 112 |
+
sent = []
|
| 113 |
+
|
| 114 |
+
if len(sent) > 0:
|
| 115 |
+
if not self._tagged:
|
| 116 |
+
sent = [w for (w, t) in sent]
|
| 117 |
+
|
| 118 |
+
if self._group_by_sent:
|
| 119 |
+
para.append(sent)
|
| 120 |
+
else:
|
| 121 |
+
para.extend(sent)
|
| 122 |
+
|
| 123 |
+
if self._group_by_para:
|
| 124 |
+
block.append(para)
|
| 125 |
+
else:
|
| 126 |
+
block.extend(para)
|
| 127 |
+
|
| 128 |
+
return block
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def demo():
|
| 132 |
+
|
| 133 |
+
import nltk
|
| 134 |
+
from nltk.corpus.util import LazyCorpusLoader
|
| 135 |
+
|
| 136 |
+
jeita = LazyCorpusLoader("jeita", ChasenCorpusReader, r".*chasen", encoding="utf-8")
|
| 137 |
+
print("/".join(jeita.words()[22100:22140]))
|
| 138 |
+
|
| 139 |
+
print(
|
| 140 |
+
"\nEOS\n".join(
|
| 141 |
+
"\n".join("{}/{}".format(w[0], w[1].split("\t")[2]) for w in sent)
|
| 142 |
+
for sent in jeita.tagged_sents()[2170:2173]
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test():
|
| 148 |
+
|
| 149 |
+
from nltk.corpus.util import LazyCorpusLoader
|
| 150 |
+
|
| 151 |
+
jeita = LazyCorpusLoader("jeita", ChasenCorpusReader, r".*chasen", encoding="utf-8")
|
| 152 |
+
|
| 153 |
+
assert isinstance(jeita.tagged_words()[0][1], str)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
demo()
|
| 158 |
+
test()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/childes.py
ADDED
|
@@ -0,0 +1,630 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CHILDES XML Corpus Reader
|
| 2 |
+
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Tomonori Nagano <tnagano@gc.cuny.edu>
|
| 5 |
+
# Alexis Dimitriadis <A.Dimitriadis@uu.nl>
|
| 6 |
+
# URL: <https://www.nltk.org/>
|
| 7 |
+
# For license information, see LICENSE.TXT
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
Corpus reader for the XML version of the CHILDES corpus.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
__docformat__ = "epytext en"
|
| 14 |
+
|
| 15 |
+
import re
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
|
| 18 |
+
from nltk.corpus.reader.util import concat
|
| 19 |
+
from nltk.corpus.reader.xmldocs import ElementTree, XMLCorpusReader
|
| 20 |
+
from nltk.util import LazyConcatenation, LazyMap, flatten
|
| 21 |
+
|
| 22 |
+
# to resolve the namespace issue
|
| 23 |
+
NS = "http://www.talkbank.org/ns/talkbank"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class CHILDESCorpusReader(XMLCorpusReader):
|
| 27 |
+
"""
|
| 28 |
+
Corpus reader for the XML version of the CHILDES corpus.
|
| 29 |
+
The CHILDES corpus is available at ``https://childes.talkbank.org/``. The XML
|
| 30 |
+
version of CHILDES is located at ``https://childes.talkbank.org/data-xml/``.
|
| 31 |
+
Copy the needed parts of the CHILDES XML corpus into the NLTK data directory
|
| 32 |
+
(``nltk_data/corpora/CHILDES/``).
|
| 33 |
+
|
| 34 |
+
For access to the file text use the usual nltk functions,
|
| 35 |
+
``words()``, ``sents()``, ``tagged_words()`` and ``tagged_sents()``.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, root, fileids, lazy=True):
|
| 39 |
+
XMLCorpusReader.__init__(self, root, fileids)
|
| 40 |
+
self._lazy = lazy
|
| 41 |
+
|
| 42 |
+
def words(
|
| 43 |
+
self,
|
| 44 |
+
fileids=None,
|
| 45 |
+
speaker="ALL",
|
| 46 |
+
stem=False,
|
| 47 |
+
relation=False,
|
| 48 |
+
strip_space=True,
|
| 49 |
+
replace=False,
|
| 50 |
+
):
|
| 51 |
+
"""
|
| 52 |
+
:return: the given file(s) as a list of words
|
| 53 |
+
:rtype: list(str)
|
| 54 |
+
|
| 55 |
+
:param speaker: If specified, select specific speaker(s) defined
|
| 56 |
+
in the corpus. Default is 'ALL' (all participants). Common choices
|
| 57 |
+
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
|
| 58 |
+
researchers)
|
| 59 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 60 |
+
:param relation: If true, then return tuples of (stem, index,
|
| 61 |
+
dependent_index)
|
| 62 |
+
:param strip_space: If true, then strip trailing spaces from word
|
| 63 |
+
tokens. Otherwise, leave the spaces on the tokens.
|
| 64 |
+
:param replace: If true, then use the replaced (intended) word instead
|
| 65 |
+
of the original word (e.g., 'wat' will be replaced with 'watch')
|
| 66 |
+
"""
|
| 67 |
+
sent = None
|
| 68 |
+
pos = False
|
| 69 |
+
if not self._lazy:
|
| 70 |
+
return [
|
| 71 |
+
self._get_words(
|
| 72 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 73 |
+
)
|
| 74 |
+
for fileid in self.abspaths(fileids)
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
get_words = lambda fileid: self._get_words(
|
| 78 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 79 |
+
)
|
| 80 |
+
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
|
| 81 |
+
|
| 82 |
+
def tagged_words(
|
| 83 |
+
self,
|
| 84 |
+
fileids=None,
|
| 85 |
+
speaker="ALL",
|
| 86 |
+
stem=False,
|
| 87 |
+
relation=False,
|
| 88 |
+
strip_space=True,
|
| 89 |
+
replace=False,
|
| 90 |
+
):
|
| 91 |
+
"""
|
| 92 |
+
:return: the given file(s) as a list of tagged
|
| 93 |
+
words and punctuation symbols, encoded as tuples
|
| 94 |
+
``(word,tag)``.
|
| 95 |
+
:rtype: list(tuple(str,str))
|
| 96 |
+
|
| 97 |
+
:param speaker: If specified, select specific speaker(s) defined
|
| 98 |
+
in the corpus. Default is 'ALL' (all participants). Common choices
|
| 99 |
+
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
|
| 100 |
+
researchers)
|
| 101 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 102 |
+
:param relation: If true, then return tuples of (stem, index,
|
| 103 |
+
dependent_index)
|
| 104 |
+
:param strip_space: If true, then strip trailing spaces from word
|
| 105 |
+
tokens. Otherwise, leave the spaces on the tokens.
|
| 106 |
+
:param replace: If true, then use the replaced (intended) word instead
|
| 107 |
+
of the original word (e.g., 'wat' will be replaced with 'watch')
|
| 108 |
+
"""
|
| 109 |
+
sent = None
|
| 110 |
+
pos = True
|
| 111 |
+
if not self._lazy:
|
| 112 |
+
return [
|
| 113 |
+
self._get_words(
|
| 114 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 115 |
+
)
|
| 116 |
+
for fileid in self.abspaths(fileids)
|
| 117 |
+
]
|
| 118 |
+
|
| 119 |
+
get_words = lambda fileid: self._get_words(
|
| 120 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 121 |
+
)
|
| 122 |
+
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
|
| 123 |
+
|
| 124 |
+
def sents(
|
| 125 |
+
self,
|
| 126 |
+
fileids=None,
|
| 127 |
+
speaker="ALL",
|
| 128 |
+
stem=False,
|
| 129 |
+
relation=None,
|
| 130 |
+
strip_space=True,
|
| 131 |
+
replace=False,
|
| 132 |
+
):
|
| 133 |
+
"""
|
| 134 |
+
:return: the given file(s) as a list of sentences or utterances, each
|
| 135 |
+
encoded as a list of word strings.
|
| 136 |
+
:rtype: list(list(str))
|
| 137 |
+
|
| 138 |
+
:param speaker: If specified, select specific speaker(s) defined
|
| 139 |
+
in the corpus. Default is 'ALL' (all participants). Common choices
|
| 140 |
+
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
|
| 141 |
+
researchers)
|
| 142 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 143 |
+
:param relation: If true, then return tuples of ``(str,pos,relation_list)``.
|
| 144 |
+
If there is manually-annotated relation info, it will return
|
| 145 |
+
tuples of ``(str,pos,test_relation_list,str,pos,gold_relation_list)``
|
| 146 |
+
:param strip_space: If true, then strip trailing spaces from word
|
| 147 |
+
tokens. Otherwise, leave the spaces on the tokens.
|
| 148 |
+
:param replace: If true, then use the replaced (intended) word instead
|
| 149 |
+
of the original word (e.g., 'wat' will be replaced with 'watch')
|
| 150 |
+
"""
|
| 151 |
+
sent = True
|
| 152 |
+
pos = False
|
| 153 |
+
if not self._lazy:
|
| 154 |
+
return [
|
| 155 |
+
self._get_words(
|
| 156 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 157 |
+
)
|
| 158 |
+
for fileid in self.abspaths(fileids)
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
get_words = lambda fileid: self._get_words(
|
| 162 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 163 |
+
)
|
| 164 |
+
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
|
| 165 |
+
|
| 166 |
+
def tagged_sents(
|
| 167 |
+
self,
|
| 168 |
+
fileids=None,
|
| 169 |
+
speaker="ALL",
|
| 170 |
+
stem=False,
|
| 171 |
+
relation=None,
|
| 172 |
+
strip_space=True,
|
| 173 |
+
replace=False,
|
| 174 |
+
):
|
| 175 |
+
"""
|
| 176 |
+
:return: the given file(s) as a list of
|
| 177 |
+
sentences, each encoded as a list of ``(word,tag)`` tuples.
|
| 178 |
+
:rtype: list(list(tuple(str,str)))
|
| 179 |
+
|
| 180 |
+
:param speaker: If specified, select specific speaker(s) defined
|
| 181 |
+
in the corpus. Default is 'ALL' (all participants). Common choices
|
| 182 |
+
are 'CHI' (the child), 'MOT' (mother), ['CHI','MOT'] (exclude
|
| 183 |
+
researchers)
|
| 184 |
+
:param stem: If true, then use word stems instead of word strings.
|
| 185 |
+
:param relation: If true, then return tuples of ``(str,pos,relation_list)``.
|
| 186 |
+
If there is manually-annotated relation info, it will return
|
| 187 |
+
tuples of ``(str,pos,test_relation_list,str,pos,gold_relation_list)``
|
| 188 |
+
:param strip_space: If true, then strip trailing spaces from word
|
| 189 |
+
tokens. Otherwise, leave the spaces on the tokens.
|
| 190 |
+
:param replace: If true, then use the replaced (intended) word instead
|
| 191 |
+
of the original word (e.g., 'wat' will be replaced with 'watch')
|
| 192 |
+
"""
|
| 193 |
+
sent = True
|
| 194 |
+
pos = True
|
| 195 |
+
if not self._lazy:
|
| 196 |
+
return [
|
| 197 |
+
self._get_words(
|
| 198 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 199 |
+
)
|
| 200 |
+
for fileid in self.abspaths(fileids)
|
| 201 |
+
]
|
| 202 |
+
|
| 203 |
+
get_words = lambda fileid: self._get_words(
|
| 204 |
+
fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 205 |
+
)
|
| 206 |
+
return LazyConcatenation(LazyMap(get_words, self.abspaths(fileids)))
|
| 207 |
+
|
| 208 |
+
def corpus(self, fileids=None):
|
| 209 |
+
"""
|
| 210 |
+
:return: the given file(s) as a dict of ``(corpus_property_key, value)``
|
| 211 |
+
:rtype: list(dict)
|
| 212 |
+
"""
|
| 213 |
+
if not self._lazy:
|
| 214 |
+
return [self._get_corpus(fileid) for fileid in self.abspaths(fileids)]
|
| 215 |
+
return LazyMap(self._get_corpus, self.abspaths(fileids))
|
| 216 |
+
|
| 217 |
+
def _get_corpus(self, fileid):
|
| 218 |
+
results = dict()
|
| 219 |
+
xmldoc = ElementTree.parse(fileid).getroot()
|
| 220 |
+
for key, value in xmldoc.items():
|
| 221 |
+
results[key] = value
|
| 222 |
+
return results
|
| 223 |
+
|
| 224 |
+
def participants(self, fileids=None):
|
| 225 |
+
"""
|
| 226 |
+
:return: the given file(s) as a dict of
|
| 227 |
+
``(participant_property_key, value)``
|
| 228 |
+
:rtype: list(dict)
|
| 229 |
+
"""
|
| 230 |
+
if not self._lazy:
|
| 231 |
+
return [self._get_participants(fileid) for fileid in self.abspaths(fileids)]
|
| 232 |
+
return LazyMap(self._get_participants, self.abspaths(fileids))
|
| 233 |
+
|
| 234 |
+
def _get_participants(self, fileid):
|
| 235 |
+
# multidimensional dicts
|
| 236 |
+
def dictOfDicts():
|
| 237 |
+
return defaultdict(dictOfDicts)
|
| 238 |
+
|
| 239 |
+
xmldoc = ElementTree.parse(fileid).getroot()
|
| 240 |
+
# getting participants' data
|
| 241 |
+
pat = dictOfDicts()
|
| 242 |
+
for participant in xmldoc.findall(
|
| 243 |
+
f".//{{{NS}}}Participants/{{{NS}}}participant"
|
| 244 |
+
):
|
| 245 |
+
for (key, value) in participant.items():
|
| 246 |
+
pat[participant.get("id")][key] = value
|
| 247 |
+
return pat
|
| 248 |
+
|
| 249 |
+
def age(self, fileids=None, speaker="CHI", month=False):
|
| 250 |
+
"""
|
| 251 |
+
:return: the given file(s) as string or int
|
| 252 |
+
:rtype: list or int
|
| 253 |
+
|
| 254 |
+
:param month: If true, return months instead of year-month-date
|
| 255 |
+
"""
|
| 256 |
+
if not self._lazy:
|
| 257 |
+
return [
|
| 258 |
+
self._get_age(fileid, speaker, month)
|
| 259 |
+
for fileid in self.abspaths(fileids)
|
| 260 |
+
]
|
| 261 |
+
get_age = lambda fileid: self._get_age(fileid, speaker, month)
|
| 262 |
+
return LazyMap(get_age, self.abspaths(fileids))
|
| 263 |
+
|
| 264 |
+
def _get_age(self, fileid, speaker, month):
|
| 265 |
+
xmldoc = ElementTree.parse(fileid).getroot()
|
| 266 |
+
for pat in xmldoc.findall(f".//{{{NS}}}Participants/{{{NS}}}participant"):
|
| 267 |
+
try:
|
| 268 |
+
if pat.get("id") == speaker:
|
| 269 |
+
age = pat.get("age")
|
| 270 |
+
if month:
|
| 271 |
+
age = self.convert_age(age)
|
| 272 |
+
return age
|
| 273 |
+
# some files don't have age data
|
| 274 |
+
except (TypeError, AttributeError) as e:
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
def convert_age(self, age_year):
|
| 278 |
+
"Caclculate age in months from a string in CHILDES format"
|
| 279 |
+
m = re.match(r"P(\d+)Y(\d+)M?(\d?\d?)D?", age_year)
|
| 280 |
+
age_month = int(m.group(1)) * 12 + int(m.group(2))
|
| 281 |
+
try:
|
| 282 |
+
if int(m.group(3)) > 15:
|
| 283 |
+
age_month += 1
|
| 284 |
+
# some corpora don't have age information?
|
| 285 |
+
except ValueError as e:
|
| 286 |
+
pass
|
| 287 |
+
return age_month
|
| 288 |
+
|
| 289 |
+
def MLU(self, fileids=None, speaker="CHI"):
|
| 290 |
+
"""
|
| 291 |
+
:return: the given file(s) as a floating number
|
| 292 |
+
:rtype: list(float)
|
| 293 |
+
"""
|
| 294 |
+
if not self._lazy:
|
| 295 |
+
return [
|
| 296 |
+
self._getMLU(fileid, speaker=speaker)
|
| 297 |
+
for fileid in self.abspaths(fileids)
|
| 298 |
+
]
|
| 299 |
+
get_MLU = lambda fileid: self._getMLU(fileid, speaker=speaker)
|
| 300 |
+
return LazyMap(get_MLU, self.abspaths(fileids))
|
| 301 |
+
|
| 302 |
+
def _getMLU(self, fileid, speaker):
|
| 303 |
+
sents = self._get_words(
|
| 304 |
+
fileid,
|
| 305 |
+
speaker=speaker,
|
| 306 |
+
sent=True,
|
| 307 |
+
stem=True,
|
| 308 |
+
relation=False,
|
| 309 |
+
pos=True,
|
| 310 |
+
strip_space=True,
|
| 311 |
+
replace=True,
|
| 312 |
+
)
|
| 313 |
+
results = []
|
| 314 |
+
lastSent = []
|
| 315 |
+
numFillers = 0
|
| 316 |
+
sentDiscount = 0
|
| 317 |
+
for sent in sents:
|
| 318 |
+
posList = [pos for (word, pos) in sent]
|
| 319 |
+
# if any part of the sentence is intelligible
|
| 320 |
+
if any(pos == "unk" for pos in posList):
|
| 321 |
+
continue
|
| 322 |
+
# if the sentence is null
|
| 323 |
+
elif sent == []:
|
| 324 |
+
continue
|
| 325 |
+
# if the sentence is the same as the last sent
|
| 326 |
+
elif sent == lastSent:
|
| 327 |
+
continue
|
| 328 |
+
else:
|
| 329 |
+
results.append([word for (word, pos) in sent])
|
| 330 |
+
# count number of fillers
|
| 331 |
+
if len({"co", None}.intersection(posList)) > 0:
|
| 332 |
+
numFillers += posList.count("co")
|
| 333 |
+
numFillers += posList.count(None)
|
| 334 |
+
sentDiscount += 1
|
| 335 |
+
lastSent = sent
|
| 336 |
+
try:
|
| 337 |
+
thisWordList = flatten(results)
|
| 338 |
+
# count number of morphemes
|
| 339 |
+
# (e.g., 'read' = 1 morpheme but 'read-PAST' is 2 morphemes)
|
| 340 |
+
numWords = (
|
| 341 |
+
len(flatten([word.split("-") for word in thisWordList])) - numFillers
|
| 342 |
+
)
|
| 343 |
+
numSents = len(results) - sentDiscount
|
| 344 |
+
mlu = numWords / numSents
|
| 345 |
+
except ZeroDivisionError:
|
| 346 |
+
mlu = 0
|
| 347 |
+
# return {'mlu':mlu,'wordNum':numWords,'sentNum':numSents}
|
| 348 |
+
return mlu
|
| 349 |
+
|
| 350 |
+
def _get_words(
|
| 351 |
+
self, fileid, speaker, sent, stem, relation, pos, strip_space, replace
|
| 352 |
+
):
|
| 353 |
+
if (
|
| 354 |
+
isinstance(speaker, str) and speaker != "ALL"
|
| 355 |
+
): # ensure we have a list of speakers
|
| 356 |
+
speaker = [speaker]
|
| 357 |
+
xmldoc = ElementTree.parse(fileid).getroot()
|
| 358 |
+
# processing each xml doc
|
| 359 |
+
results = []
|
| 360 |
+
for xmlsent in xmldoc.findall(".//{%s}u" % NS):
|
| 361 |
+
sents = []
|
| 362 |
+
# select speakers
|
| 363 |
+
if speaker == "ALL" or xmlsent.get("who") in speaker:
|
| 364 |
+
for xmlword in xmlsent.findall(".//{%s}w" % NS):
|
| 365 |
+
infl = None
|
| 366 |
+
suffixStem = None
|
| 367 |
+
suffixTag = None
|
| 368 |
+
# getting replaced words
|
| 369 |
+
if replace and xmlsent.find(f".//{{{NS}}}w/{{{NS}}}replacement"):
|
| 370 |
+
xmlword = xmlsent.find(
|
| 371 |
+
f".//{{{NS}}}w/{{{NS}}}replacement/{{{NS}}}w"
|
| 372 |
+
)
|
| 373 |
+
elif replace and xmlsent.find(f".//{{{NS}}}w/{{{NS}}}wk"):
|
| 374 |
+
xmlword = xmlsent.find(f".//{{{NS}}}w/{{{NS}}}wk")
|
| 375 |
+
# get text
|
| 376 |
+
if xmlword.text:
|
| 377 |
+
word = xmlword.text
|
| 378 |
+
else:
|
| 379 |
+
word = ""
|
| 380 |
+
# strip tailing space
|
| 381 |
+
if strip_space:
|
| 382 |
+
word = word.strip()
|
| 383 |
+
# stem
|
| 384 |
+
if relation or stem:
|
| 385 |
+
try:
|
| 386 |
+
xmlstem = xmlword.find(".//{%s}stem" % NS)
|
| 387 |
+
word = xmlstem.text
|
| 388 |
+
except AttributeError as e:
|
| 389 |
+
pass
|
| 390 |
+
# if there is an inflection
|
| 391 |
+
try:
|
| 392 |
+
xmlinfl = xmlword.find(
|
| 393 |
+
f".//{{{NS}}}mor/{{{NS}}}mw/{{{NS}}}mk"
|
| 394 |
+
)
|
| 395 |
+
word += "-" + xmlinfl.text
|
| 396 |
+
except:
|
| 397 |
+
pass
|
| 398 |
+
# if there is a suffix
|
| 399 |
+
try:
|
| 400 |
+
xmlsuffix = xmlword.find(
|
| 401 |
+
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}stem"
|
| 402 |
+
% (NS, NS, NS, NS)
|
| 403 |
+
)
|
| 404 |
+
suffixStem = xmlsuffix.text
|
| 405 |
+
except AttributeError:
|
| 406 |
+
suffixStem = ""
|
| 407 |
+
if suffixStem:
|
| 408 |
+
word += "~" + suffixStem
|
| 409 |
+
# pos
|
| 410 |
+
if relation or pos:
|
| 411 |
+
try:
|
| 412 |
+
xmlpos = xmlword.findall(".//{%s}c" % NS)
|
| 413 |
+
xmlpos2 = xmlword.findall(".//{%s}s" % NS)
|
| 414 |
+
if xmlpos2 != []:
|
| 415 |
+
tag = xmlpos[0].text + ":" + xmlpos2[0].text
|
| 416 |
+
else:
|
| 417 |
+
tag = xmlpos[0].text
|
| 418 |
+
except (AttributeError, IndexError) as e:
|
| 419 |
+
tag = ""
|
| 420 |
+
try:
|
| 421 |
+
xmlsuffixpos = xmlword.findall(
|
| 422 |
+
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}c"
|
| 423 |
+
% (NS, NS, NS, NS, NS)
|
| 424 |
+
)
|
| 425 |
+
xmlsuffixpos2 = xmlword.findall(
|
| 426 |
+
".//{%s}mor/{%s}mor-post/{%s}mw/{%s}pos/{%s}s"
|
| 427 |
+
% (NS, NS, NS, NS, NS)
|
| 428 |
+
)
|
| 429 |
+
if xmlsuffixpos2:
|
| 430 |
+
suffixTag = (
|
| 431 |
+
xmlsuffixpos[0].text + ":" + xmlsuffixpos2[0].text
|
| 432 |
+
)
|
| 433 |
+
else:
|
| 434 |
+
suffixTag = xmlsuffixpos[0].text
|
| 435 |
+
except:
|
| 436 |
+
pass
|
| 437 |
+
if suffixTag:
|
| 438 |
+
tag += "~" + suffixTag
|
| 439 |
+
word = (word, tag)
|
| 440 |
+
# relational
|
| 441 |
+
# the gold standard is stored in
|
| 442 |
+
# <mor></mor><mor type="trn"><gra type="grt">
|
| 443 |
+
if relation == True:
|
| 444 |
+
for xmlstem_rel in xmlword.findall(
|
| 445 |
+
f".//{{{NS}}}mor/{{{NS}}}gra"
|
| 446 |
+
):
|
| 447 |
+
if not xmlstem_rel.get("type") == "grt":
|
| 448 |
+
word = (
|
| 449 |
+
word[0],
|
| 450 |
+
word[1],
|
| 451 |
+
xmlstem_rel.get("index")
|
| 452 |
+
+ "|"
|
| 453 |
+
+ xmlstem_rel.get("head")
|
| 454 |
+
+ "|"
|
| 455 |
+
+ xmlstem_rel.get("relation"),
|
| 456 |
+
)
|
| 457 |
+
else:
|
| 458 |
+
word = (
|
| 459 |
+
word[0],
|
| 460 |
+
word[1],
|
| 461 |
+
word[2],
|
| 462 |
+
word[0],
|
| 463 |
+
word[1],
|
| 464 |
+
xmlstem_rel.get("index")
|
| 465 |
+
+ "|"
|
| 466 |
+
+ xmlstem_rel.get("head")
|
| 467 |
+
+ "|"
|
| 468 |
+
+ xmlstem_rel.get("relation"),
|
| 469 |
+
)
|
| 470 |
+
try:
|
| 471 |
+
for xmlpost_rel in xmlword.findall(
|
| 472 |
+
f".//{{{NS}}}mor/{{{NS}}}mor-post/{{{NS}}}gra"
|
| 473 |
+
):
|
| 474 |
+
if not xmlpost_rel.get("type") == "grt":
|
| 475 |
+
suffixStem = (
|
| 476 |
+
suffixStem[0],
|
| 477 |
+
suffixStem[1],
|
| 478 |
+
xmlpost_rel.get("index")
|
| 479 |
+
+ "|"
|
| 480 |
+
+ xmlpost_rel.get("head")
|
| 481 |
+
+ "|"
|
| 482 |
+
+ xmlpost_rel.get("relation"),
|
| 483 |
+
)
|
| 484 |
+
else:
|
| 485 |
+
suffixStem = (
|
| 486 |
+
suffixStem[0],
|
| 487 |
+
suffixStem[1],
|
| 488 |
+
suffixStem[2],
|
| 489 |
+
suffixStem[0],
|
| 490 |
+
suffixStem[1],
|
| 491 |
+
xmlpost_rel.get("index")
|
| 492 |
+
+ "|"
|
| 493 |
+
+ xmlpost_rel.get("head")
|
| 494 |
+
+ "|"
|
| 495 |
+
+ xmlpost_rel.get("relation"),
|
| 496 |
+
)
|
| 497 |
+
except:
|
| 498 |
+
pass
|
| 499 |
+
sents.append(word)
|
| 500 |
+
if sent or relation:
|
| 501 |
+
results.append(sents)
|
| 502 |
+
else:
|
| 503 |
+
results.extend(sents)
|
| 504 |
+
return LazyMap(lambda x: x, results)
|
| 505 |
+
|
| 506 |
+
# Ready-to-use browser opener
|
| 507 |
+
|
| 508 |
+
"""
|
| 509 |
+
The base URL for viewing files on the childes website. This
|
| 510 |
+
shouldn't need to be changed, unless CHILDES changes the configuration
|
| 511 |
+
of their server or unless the user sets up their own corpus webserver.
|
| 512 |
+
"""
|
| 513 |
+
childes_url_base = r"https://childes.talkbank.org/browser/index.php?url="
|
| 514 |
+
|
| 515 |
+
def webview_file(self, fileid, urlbase=None):
|
| 516 |
+
"""Map a corpus file to its web version on the CHILDES website,
|
| 517 |
+
and open it in a web browser.
|
| 518 |
+
|
| 519 |
+
The complete URL to be used is:
|
| 520 |
+
childes.childes_url_base + urlbase + fileid.replace('.xml', '.cha')
|
| 521 |
+
|
| 522 |
+
If no urlbase is passed, we try to calculate it. This
|
| 523 |
+
requires that the childes corpus was set up to mirror the
|
| 524 |
+
folder hierarchy under childes.psy.cmu.edu/data-xml/, e.g.:
|
| 525 |
+
nltk_data/corpora/childes/Eng-USA/Cornell/??? or
|
| 526 |
+
nltk_data/corpora/childes/Romance/Spanish/Aguirre/???
|
| 527 |
+
|
| 528 |
+
The function first looks (as a special case) if "Eng-USA" is
|
| 529 |
+
on the path consisting of <corpus root>+fileid; then if
|
| 530 |
+
"childes", possibly followed by "data-xml", appears. If neither
|
| 531 |
+
one is found, we use the unmodified fileid and hope for the best.
|
| 532 |
+
If this is not right, specify urlbase explicitly, e.g., if the
|
| 533 |
+
corpus root points to the Cornell folder, urlbase='Eng-USA/Cornell'.
|
| 534 |
+
"""
|
| 535 |
+
|
| 536 |
+
import webbrowser
|
| 537 |
+
|
| 538 |
+
if urlbase:
|
| 539 |
+
path = urlbase + "/" + fileid
|
| 540 |
+
else:
|
| 541 |
+
full = self.root + "/" + fileid
|
| 542 |
+
full = re.sub(r"\\", "/", full)
|
| 543 |
+
if "/childes/" in full.lower():
|
| 544 |
+
# Discard /data-xml/ if present
|
| 545 |
+
path = re.findall(r"(?i)/childes(?:/data-xml)?/(.*)\.xml", full)[0]
|
| 546 |
+
elif "eng-usa" in full.lower():
|
| 547 |
+
path = "Eng-USA/" + re.findall(r"/(?i)Eng-USA/(.*)\.xml", full)[0]
|
| 548 |
+
else:
|
| 549 |
+
path = fileid
|
| 550 |
+
|
| 551 |
+
# Strip ".xml" and add ".cha", as necessary:
|
| 552 |
+
if path.endswith(".xml"):
|
| 553 |
+
path = path[:-4]
|
| 554 |
+
|
| 555 |
+
if not path.endswith(".cha"):
|
| 556 |
+
path = path + ".cha"
|
| 557 |
+
|
| 558 |
+
url = self.childes_url_base + path
|
| 559 |
+
|
| 560 |
+
webbrowser.open_new_tab(url)
|
| 561 |
+
print("Opening in browser:", url)
|
| 562 |
+
# Pausing is a good idea, but it's up to the user...
|
| 563 |
+
# raw_input("Hit Return to continue")
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def demo(corpus_root=None):
|
| 567 |
+
"""
|
| 568 |
+
The CHILDES corpus should be manually downloaded and saved
|
| 569 |
+
to ``[NLTK_Data_Dir]/corpora/childes/``
|
| 570 |
+
"""
|
| 571 |
+
if not corpus_root:
|
| 572 |
+
from nltk.data import find
|
| 573 |
+
|
| 574 |
+
corpus_root = find("corpora/childes/data-xml/Eng-USA/")
|
| 575 |
+
|
| 576 |
+
try:
|
| 577 |
+
childes = CHILDESCorpusReader(corpus_root, ".*.xml")
|
| 578 |
+
# describe all corpus
|
| 579 |
+
for file in childes.fileids()[:5]:
|
| 580 |
+
corpus = ""
|
| 581 |
+
corpus_id = ""
|
| 582 |
+
for (key, value) in childes.corpus(file)[0].items():
|
| 583 |
+
if key == "Corpus":
|
| 584 |
+
corpus = value
|
| 585 |
+
if key == "Id":
|
| 586 |
+
corpus_id = value
|
| 587 |
+
print("Reading", corpus, corpus_id, " .....")
|
| 588 |
+
print("words:", childes.words(file)[:7], "...")
|
| 589 |
+
print(
|
| 590 |
+
"words with replaced words:",
|
| 591 |
+
childes.words(file, replace=True)[:7],
|
| 592 |
+
" ...",
|
| 593 |
+
)
|
| 594 |
+
print("words with pos tags:", childes.tagged_words(file)[:7], " ...")
|
| 595 |
+
print("words (only MOT):", childes.words(file, speaker="MOT")[:7], "...")
|
| 596 |
+
print("words (only CHI):", childes.words(file, speaker="CHI")[:7], "...")
|
| 597 |
+
print("stemmed words:", childes.words(file, stem=True)[:7], " ...")
|
| 598 |
+
print(
|
| 599 |
+
"words with relations and pos-tag:",
|
| 600 |
+
childes.words(file, relation=True)[:5],
|
| 601 |
+
" ...",
|
| 602 |
+
)
|
| 603 |
+
print("sentence:", childes.sents(file)[:2], " ...")
|
| 604 |
+
for (participant, values) in childes.participants(file)[0].items():
|
| 605 |
+
for (key, value) in values.items():
|
| 606 |
+
print("\tparticipant", participant, key, ":", value)
|
| 607 |
+
print("num of sent:", len(childes.sents(file)))
|
| 608 |
+
print("num of morphemes:", len(childes.words(file, stem=True)))
|
| 609 |
+
print("age:", childes.age(file))
|
| 610 |
+
print("age in month:", childes.age(file, month=True))
|
| 611 |
+
print("MLU:", childes.MLU(file))
|
| 612 |
+
print()
|
| 613 |
+
|
| 614 |
+
except LookupError as e:
|
| 615 |
+
print(
|
| 616 |
+
"""The CHILDES corpus, or the parts you need, should be manually
|
| 617 |
+
downloaded from https://childes.talkbank.org/data-xml/ and saved at
|
| 618 |
+
[NLTK_Data_Dir]/corpora/childes/
|
| 619 |
+
Alternately, you can call the demo with the path to a portion of the CHILDES corpus, e.g.:
|
| 620 |
+
demo('/path/to/childes/data-xml/Eng-USA/")
|
| 621 |
+
"""
|
| 622 |
+
)
|
| 623 |
+
# corpus_root_http = urllib2.urlopen('https://childes.talkbank.org/data-xml/Eng-USA/Bates.zip')
|
| 624 |
+
# corpus_root_http_bates = zipfile.ZipFile(cStringIO.StringIO(corpus_root_http.read()))
|
| 625 |
+
##this fails
|
| 626 |
+
# childes = CHILDESCorpusReader(corpus_root_http_bates,corpus_root_http_bates.namelist())
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
if __name__ == "__main__":
|
| 630 |
+
demo()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/chunked.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Chunked Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 5 |
+
# Edward Loper <edloper@gmail.com>
|
| 6 |
+
# URL: <https://www.nltk.org/>
|
| 7 |
+
# For license information, see LICENSE.TXT
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
A reader for corpora that contain chunked (and optionally tagged)
|
| 11 |
+
documents.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import codecs
|
| 15 |
+
import os.path
|
| 16 |
+
|
| 17 |
+
import nltk
|
| 18 |
+
from nltk.chunk import tagstr2tree
|
| 19 |
+
from nltk.corpus.reader.api import *
|
| 20 |
+
from nltk.corpus.reader.bracket_parse import BracketParseCorpusReader
|
| 21 |
+
from nltk.corpus.reader.util import *
|
| 22 |
+
from nltk.tokenize import *
|
| 23 |
+
from nltk.tree import Tree
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ChunkedCorpusReader(CorpusReader):
|
| 27 |
+
"""
|
| 28 |
+
Reader for chunked (and optionally tagged) corpora. Paragraphs
|
| 29 |
+
are split using a block reader. They are then tokenized into
|
| 30 |
+
sentences using a sentence tokenizer. Finally, these sentences
|
| 31 |
+
are parsed into chunk trees using a string-to-chunktree conversion
|
| 32 |
+
function. Each of these steps can be performed using a default
|
| 33 |
+
function or a custom function. By default, paragraphs are split
|
| 34 |
+
on blank lines; sentences are listed one per line; and sentences
|
| 35 |
+
are parsed into chunk trees using ``nltk.chunk.tagstr2tree``.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
root,
|
| 41 |
+
fileids,
|
| 42 |
+
extension="",
|
| 43 |
+
str2chunktree=tagstr2tree,
|
| 44 |
+
sent_tokenizer=RegexpTokenizer("\n", gaps=True),
|
| 45 |
+
para_block_reader=read_blankline_block,
|
| 46 |
+
encoding="utf8",
|
| 47 |
+
tagset=None,
|
| 48 |
+
):
|
| 49 |
+
"""
|
| 50 |
+
:param root: The root directory for this corpus.
|
| 51 |
+
:param fileids: A list or regexp specifying the fileids in this corpus.
|
| 52 |
+
"""
|
| 53 |
+
CorpusReader.__init__(self, root, fileids, encoding)
|
| 54 |
+
self._cv_args = (str2chunktree, sent_tokenizer, para_block_reader, tagset)
|
| 55 |
+
"""Arguments for corpus views generated by this corpus: a tuple
|
| 56 |
+
(str2chunktree, sent_tokenizer, para_block_tokenizer)"""
|
| 57 |
+
|
| 58 |
+
def words(self, fileids=None):
|
| 59 |
+
"""
|
| 60 |
+
:return: the given file(s) as a list of words
|
| 61 |
+
and punctuation symbols.
|
| 62 |
+
:rtype: list(str)
|
| 63 |
+
"""
|
| 64 |
+
return concat(
|
| 65 |
+
[
|
| 66 |
+
ChunkedCorpusView(f, enc, 0, 0, 0, 0, *self._cv_args)
|
| 67 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 68 |
+
]
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
def sents(self, fileids=None):
|
| 72 |
+
"""
|
| 73 |
+
:return: the given file(s) as a list of
|
| 74 |
+
sentences or utterances, each encoded as a list of word
|
| 75 |
+
strings.
|
| 76 |
+
:rtype: list(list(str))
|
| 77 |
+
"""
|
| 78 |
+
return concat(
|
| 79 |
+
[
|
| 80 |
+
ChunkedCorpusView(f, enc, 0, 1, 0, 0, *self._cv_args)
|
| 81 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 82 |
+
]
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def paras(self, fileids=None):
|
| 86 |
+
"""
|
| 87 |
+
:return: the given file(s) as a list of
|
| 88 |
+
paragraphs, each encoded as a list of sentences, which are
|
| 89 |
+
in turn encoded as lists of word strings.
|
| 90 |
+
:rtype: list(list(list(str)))
|
| 91 |
+
"""
|
| 92 |
+
return concat(
|
| 93 |
+
[
|
| 94 |
+
ChunkedCorpusView(f, enc, 0, 1, 1, 0, *self._cv_args)
|
| 95 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 96 |
+
]
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
def tagged_words(self, fileids=None, tagset=None):
|
| 100 |
+
"""
|
| 101 |
+
:return: the given file(s) as a list of tagged
|
| 102 |
+
words and punctuation symbols, encoded as tuples
|
| 103 |
+
``(word,tag)``.
|
| 104 |
+
:rtype: list(tuple(str,str))
|
| 105 |
+
"""
|
| 106 |
+
return concat(
|
| 107 |
+
[
|
| 108 |
+
ChunkedCorpusView(
|
| 109 |
+
f, enc, 1, 0, 0, 0, *self._cv_args, target_tagset=tagset
|
| 110 |
+
)
|
| 111 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 112 |
+
]
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
def tagged_sents(self, fileids=None, tagset=None):
|
| 116 |
+
"""
|
| 117 |
+
:return: the given file(s) as a list of
|
| 118 |
+
sentences, each encoded as a list of ``(word,tag)`` tuples.
|
| 119 |
+
|
| 120 |
+
:rtype: list(list(tuple(str,str)))
|
| 121 |
+
"""
|
| 122 |
+
return concat(
|
| 123 |
+
[
|
| 124 |
+
ChunkedCorpusView(
|
| 125 |
+
f, enc, 1, 1, 0, 0, *self._cv_args, target_tagset=tagset
|
| 126 |
+
)
|
| 127 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 128 |
+
]
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
def tagged_paras(self, fileids=None, tagset=None):
|
| 132 |
+
"""
|
| 133 |
+
:return: the given file(s) as a list of
|
| 134 |
+
paragraphs, each encoded as a list of sentences, which are
|
| 135 |
+
in turn encoded as lists of ``(word,tag)`` tuples.
|
| 136 |
+
:rtype: list(list(list(tuple(str,str))))
|
| 137 |
+
"""
|
| 138 |
+
return concat(
|
| 139 |
+
[
|
| 140 |
+
ChunkedCorpusView(
|
| 141 |
+
f, enc, 1, 1, 1, 0, *self._cv_args, target_tagset=tagset
|
| 142 |
+
)
|
| 143 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 144 |
+
]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def chunked_words(self, fileids=None, tagset=None):
|
| 148 |
+
"""
|
| 149 |
+
:return: the given file(s) as a list of tagged
|
| 150 |
+
words and chunks. Words are encoded as ``(word, tag)``
|
| 151 |
+
tuples (if the corpus has tags) or word strings (if the
|
| 152 |
+
corpus has no tags). Chunks are encoded as depth-one
|
| 153 |
+
trees over ``(word,tag)`` tuples or word strings.
|
| 154 |
+
:rtype: list(tuple(str,str) and Tree)
|
| 155 |
+
"""
|
| 156 |
+
return concat(
|
| 157 |
+
[
|
| 158 |
+
ChunkedCorpusView(
|
| 159 |
+
f, enc, 1, 0, 0, 1, *self._cv_args, target_tagset=tagset
|
| 160 |
+
)
|
| 161 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 162 |
+
]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def chunked_sents(self, fileids=None, tagset=None):
|
| 166 |
+
"""
|
| 167 |
+
:return: the given file(s) as a list of
|
| 168 |
+
sentences, each encoded as a shallow Tree. The leaves
|
| 169 |
+
of these trees are encoded as ``(word, tag)`` tuples (if
|
| 170 |
+
the corpus has tags) or word strings (if the corpus has no
|
| 171 |
+
tags).
|
| 172 |
+
:rtype: list(Tree)
|
| 173 |
+
"""
|
| 174 |
+
return concat(
|
| 175 |
+
[
|
| 176 |
+
ChunkedCorpusView(
|
| 177 |
+
f, enc, 1, 1, 0, 1, *self._cv_args, target_tagset=tagset
|
| 178 |
+
)
|
| 179 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 180 |
+
]
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
def chunked_paras(self, fileids=None, tagset=None):
|
| 184 |
+
"""
|
| 185 |
+
:return: the given file(s) as a list of
|
| 186 |
+
paragraphs, each encoded as a list of sentences, which are
|
| 187 |
+
in turn encoded as a shallow Tree. The leaves of these
|
| 188 |
+
trees are encoded as ``(word, tag)`` tuples (if the corpus
|
| 189 |
+
has tags) or word strings (if the corpus has no tags).
|
| 190 |
+
:rtype: list(list(Tree))
|
| 191 |
+
"""
|
| 192 |
+
return concat(
|
| 193 |
+
[
|
| 194 |
+
ChunkedCorpusView(
|
| 195 |
+
f, enc, 1, 1, 1, 1, *self._cv_args, target_tagset=tagset
|
| 196 |
+
)
|
| 197 |
+
for (f, enc) in self.abspaths(fileids, True)
|
| 198 |
+
]
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def _read_block(self, stream):
|
| 202 |
+
return [tagstr2tree(t) for t in read_blankline_block(stream)]
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class ChunkedCorpusView(StreamBackedCorpusView):
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
fileid,
|
| 209 |
+
encoding,
|
| 210 |
+
tagged,
|
| 211 |
+
group_by_sent,
|
| 212 |
+
group_by_para,
|
| 213 |
+
chunked,
|
| 214 |
+
str2chunktree,
|
| 215 |
+
sent_tokenizer,
|
| 216 |
+
para_block_reader,
|
| 217 |
+
source_tagset=None,
|
| 218 |
+
target_tagset=None,
|
| 219 |
+
):
|
| 220 |
+
StreamBackedCorpusView.__init__(self, fileid, encoding=encoding)
|
| 221 |
+
self._tagged = tagged
|
| 222 |
+
self._group_by_sent = group_by_sent
|
| 223 |
+
self._group_by_para = group_by_para
|
| 224 |
+
self._chunked = chunked
|
| 225 |
+
self._str2chunktree = str2chunktree
|
| 226 |
+
self._sent_tokenizer = sent_tokenizer
|
| 227 |
+
self._para_block_reader = para_block_reader
|
| 228 |
+
self._source_tagset = source_tagset
|
| 229 |
+
self._target_tagset = target_tagset
|
| 230 |
+
|
| 231 |
+
def read_block(self, stream):
|
| 232 |
+
block = []
|
| 233 |
+
for para_str in self._para_block_reader(stream):
|
| 234 |
+
para = []
|
| 235 |
+
for sent_str in self._sent_tokenizer.tokenize(para_str):
|
| 236 |
+
sent = self._str2chunktree(
|
| 237 |
+
sent_str,
|
| 238 |
+
source_tagset=self._source_tagset,
|
| 239 |
+
target_tagset=self._target_tagset,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# If requested, throw away the tags.
|
| 243 |
+
if not self._tagged:
|
| 244 |
+
sent = self._untag(sent)
|
| 245 |
+
|
| 246 |
+
# If requested, throw away the chunks.
|
| 247 |
+
if not self._chunked:
|
| 248 |
+
sent = sent.leaves()
|
| 249 |
+
|
| 250 |
+
# Add the sentence to `para`.
|
| 251 |
+
if self._group_by_sent:
|
| 252 |
+
para.append(sent)
|
| 253 |
+
else:
|
| 254 |
+
para.extend(sent)
|
| 255 |
+
|
| 256 |
+
# Add the paragraph to `block`.
|
| 257 |
+
if self._group_by_para:
|
| 258 |
+
block.append(para)
|
| 259 |
+
else:
|
| 260 |
+
block.extend(para)
|
| 261 |
+
|
| 262 |
+
# Return the block
|
| 263 |
+
return block
|
| 264 |
+
|
| 265 |
+
def _untag(self, tree):
|
| 266 |
+
for i, child in enumerate(tree):
|
| 267 |
+
if isinstance(child, Tree):
|
| 268 |
+
self._untag(child)
|
| 269 |
+
elif isinstance(child, tuple):
|
| 270 |
+
tree[i] = child[0]
|
| 271 |
+
else:
|
| 272 |
+
raise ValueError("expected child to be Tree or tuple")
|
| 273 |
+
return tree
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/cmudict.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Carnegie Mellon Pronouncing Dictionary Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Steven Bird <stevenbird1@gmail.com>
|
| 5 |
+
# URL: <https://www.nltk.org/>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
The Carnegie Mellon Pronouncing Dictionary [cmudict.0.6]
|
| 10 |
+
ftp://ftp.cs.cmu.edu/project/speech/dict/
|
| 11 |
+
Copyright 1998 Carnegie Mellon University
|
| 12 |
+
|
| 13 |
+
File Format: Each line consists of an uppercased word, a counter
|
| 14 |
+
(for alternative pronunciations), and a transcription. Vowels are
|
| 15 |
+
marked for stress (1=primary, 2=secondary, 0=no stress). E.g.:
|
| 16 |
+
NATURAL 1 N AE1 CH ER0 AH0 L
|
| 17 |
+
|
| 18 |
+
The dictionary contains 127069 entries. Of these, 119400 words are assigned
|
| 19 |
+
a unique pronunciation, 6830 words have two pronunciations, and 839 words have
|
| 20 |
+
three or more pronunciations. Many of these are fast-speech variants.
|
| 21 |
+
|
| 22 |
+
Phonemes: There are 39 phonemes, as shown below:
|
| 23 |
+
|
| 24 |
+
Phoneme Example Translation Phoneme Example Translation
|
| 25 |
+
------- ------- ----------- ------- ------- -----------
|
| 26 |
+
AA odd AA D AE at AE T
|
| 27 |
+
AH hut HH AH T AO ought AO T
|
| 28 |
+
AW cow K AW AY hide HH AY D
|
| 29 |
+
B be B IY CH cheese CH IY Z
|
| 30 |
+
D dee D IY DH thee DH IY
|
| 31 |
+
EH Ed EH D ER hurt HH ER T
|
| 32 |
+
EY ate EY T F fee F IY
|
| 33 |
+
G green G R IY N HH he HH IY
|
| 34 |
+
IH it IH T IY eat IY T
|
| 35 |
+
JH gee JH IY K key K IY
|
| 36 |
+
L lee L IY M me M IY
|
| 37 |
+
N knee N IY NG ping P IH NG
|
| 38 |
+
OW oat OW T OY toy T OY
|
| 39 |
+
P pee P IY R read R IY D
|
| 40 |
+
S sea S IY SH she SH IY
|
| 41 |
+
T tea T IY TH theta TH EY T AH
|
| 42 |
+
UH hood HH UH D UW two T UW
|
| 43 |
+
V vee V IY W we W IY
|
| 44 |
+
Y yield Y IY L D Z zee Z IY
|
| 45 |
+
ZH seizure S IY ZH ER
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
from nltk.corpus.reader.api import *
|
| 49 |
+
from nltk.corpus.reader.util import *
|
| 50 |
+
from nltk.util import Index
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class CMUDictCorpusReader(CorpusReader):
|
| 54 |
+
def entries(self):
|
| 55 |
+
"""
|
| 56 |
+
:return: the cmudict lexicon as a list of entries
|
| 57 |
+
containing (word, transcriptions) tuples.
|
| 58 |
+
"""
|
| 59 |
+
return concat(
|
| 60 |
+
[
|
| 61 |
+
StreamBackedCorpusView(fileid, read_cmudict_block, encoding=enc)
|
| 62 |
+
for fileid, enc in self.abspaths(None, True)
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def words(self):
|
| 67 |
+
"""
|
| 68 |
+
:return: a list of all words defined in the cmudict lexicon.
|
| 69 |
+
"""
|
| 70 |
+
return [word.lower() for (word, _) in self.entries()]
|
| 71 |
+
|
| 72 |
+
def dict(self):
|
| 73 |
+
"""
|
| 74 |
+
:return: the cmudict lexicon as a dictionary, whose keys are
|
| 75 |
+
lowercase words and whose values are lists of pronunciations.
|
| 76 |
+
"""
|
| 77 |
+
return dict(Index(self.entries()))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def read_cmudict_block(stream):
|
| 81 |
+
entries = []
|
| 82 |
+
while len(entries) < 100: # Read 100 at a time.
|
| 83 |
+
line = stream.readline()
|
| 84 |
+
if line == "":
|
| 85 |
+
return entries # end of file.
|
| 86 |
+
pieces = line.split()
|
| 87 |
+
entries.append((pieces[0].lower(), pieces[2:]))
|
| 88 |
+
return entries
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/nltk/corpus/reader/comparative_sents.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Natural Language Toolkit: Comparative Sentence Corpus Reader
|
| 2 |
+
#
|
| 3 |
+
# Copyright (C) 2001-2023 NLTK Project
|
| 4 |
+
# Author: Pierpaolo Pantone <24alsecondo@gmail.com>
|
| 5 |
+
# URL: <https://www.nltk.org/>
|
| 6 |
+
# For license information, see LICENSE.TXT
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
CorpusReader for the Comparative Sentence Dataset.
|
| 10 |
+
|
| 11 |
+
- Comparative Sentence Dataset information -
|
| 12 |
+
|
| 13 |
+
Annotated by: Nitin Jindal and Bing Liu, 2006.
|
| 14 |
+
Department of Computer Sicence
|
| 15 |
+
University of Illinois at Chicago
|
| 16 |
+
|
| 17 |
+
Contact: Nitin Jindal, njindal@cs.uic.edu
|
| 18 |
+
Bing Liu, liub@cs.uic.edu (https://www.cs.uic.edu/~liub)
|
| 19 |
+
|
| 20 |
+
Distributed with permission.
|
| 21 |
+
|
| 22 |
+
Related papers:
|
| 23 |
+
|
| 24 |
+
- Nitin Jindal and Bing Liu. "Identifying Comparative Sentences in Text Documents".
|
| 25 |
+
Proceedings of the ACM SIGIR International Conference on Information Retrieval
|
| 26 |
+
(SIGIR-06), 2006.
|
| 27 |
+
|
| 28 |
+
- Nitin Jindal and Bing Liu. "Mining Comprative Sentences and Relations".
|
| 29 |
+
Proceedings of Twenty First National Conference on Artificial Intelligence
|
| 30 |
+
(AAAI-2006), 2006.
|
| 31 |
+
|
| 32 |
+
- Murthy Ganapathibhotla and Bing Liu. "Mining Opinions in Comparative Sentences".
|
| 33 |
+
Proceedings of the 22nd International Conference on Computational Linguistics
|
| 34 |
+
(Coling-2008), Manchester, 18-22 August, 2008.
|
| 35 |
+
"""
|
| 36 |
+
import re
|
| 37 |
+
|
| 38 |
+
from nltk.corpus.reader.api import *
|
| 39 |
+
from nltk.tokenize import *
|
| 40 |
+
|
| 41 |
+
# Regular expressions for dataset components
|
| 42 |
+
STARS = re.compile(r"^\*+$")
|
| 43 |
+
COMPARISON = re.compile(r"<cs-[1234]>")
|
| 44 |
+
CLOSE_COMPARISON = re.compile(r"</cs-[1234]>")
|
| 45 |
+
GRAD_COMPARISON = re.compile(r"<cs-[123]>")
|
| 46 |
+
NON_GRAD_COMPARISON = re.compile(r"<cs-4>")
|
| 47 |
+
ENTITIES_FEATS = re.compile(r"(\d)_((?:[\.\w\s/-](?!\d_))+)")
|
| 48 |
+
KEYWORD = re.compile(r"\(([^\(]*)\)$")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Comparison:
|
| 52 |
+
"""
|
| 53 |
+
A Comparison represents a comparative sentence and its constituents.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
text=None,
|
| 59 |
+
comp_type=None,
|
| 60 |
+
entity_1=None,
|
| 61 |
+
entity_2=None,
|
| 62 |
+
feature=None,
|
| 63 |
+
keyword=None,
|
| 64 |
+
):
|
| 65 |
+
"""
|
| 66 |
+
:param text: a string (optionally tokenized) containing a comparison.
|
| 67 |
+
:param comp_type: an integer defining the type of comparison expressed.
|
| 68 |
+
Values can be: 1 (Non-equal gradable), 2 (Equative), 3 (Superlative),
|
| 69 |
+
4 (Non-gradable).
|
| 70 |
+
:param entity_1: the first entity considered in the comparison relation.
|
| 71 |
+
:param entity_2: the second entity considered in the comparison relation.
|
| 72 |
+
:param feature: the feature considered in the comparison relation.
|
| 73 |
+
:param keyword: the word or phrase which is used for that comparative relation.
|
| 74 |
+
"""
|
| 75 |
+
self.text = text
|
| 76 |
+
self.comp_type = comp_type
|
| 77 |
+
self.entity_1 = entity_1
|
| 78 |
+
self.entity_2 = entity_2
|
| 79 |
+
self.feature = feature
|
| 80 |
+
self.keyword = keyword
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
return (
|
| 84 |
+
'Comparison(text="{}", comp_type={}, entity_1="{}", entity_2="{}", '
|
| 85 |
+
'feature="{}", keyword="{}")'
|
| 86 |
+
).format(
|
| 87 |
+
self.text,
|
| 88 |
+
self.comp_type,
|
| 89 |
+
self.entity_1,
|
| 90 |
+
self.entity_2,
|
| 91 |
+
self.feature,
|
| 92 |
+
self.keyword,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class ComparativeSentencesCorpusReader(CorpusReader):
|
| 97 |
+
"""
|
| 98 |
+
Reader for the Comparative Sentence Dataset by Jindal and Liu (2006).
|
| 99 |
+
|
| 100 |
+
>>> from nltk.corpus import comparative_sentences
|
| 101 |
+
>>> comparison = comparative_sentences.comparisons()[0]
|
| 102 |
+
>>> comparison.text # doctest: +NORMALIZE_WHITESPACE
|
| 103 |
+
['its', 'fast-forward', 'and', 'rewind', 'work', 'much', 'more', 'smoothly',
|
| 104 |
+
'and', 'consistently', 'than', 'those', 'of', 'other', 'models', 'i', "'ve",
|
| 105 |
+
'had', '.']
|
| 106 |
+
>>> comparison.entity_2
|
| 107 |
+
'models'
|
| 108 |
+
>>> (comparison.feature, comparison.keyword)
|
| 109 |
+
('rewind', 'more')
|
| 110 |
+
>>> len(comparative_sentences.comparisons())
|
| 111 |
+
853
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
CorpusView = StreamBackedCorpusView
|
| 115 |
+
|
| 116 |
+
def __init__(
|
| 117 |
+
self,
|
| 118 |
+
root,
|
| 119 |
+
fileids,
|
| 120 |
+
word_tokenizer=WhitespaceTokenizer(),
|
| 121 |
+
sent_tokenizer=None,
|
| 122 |
+
encoding="utf8",
|
| 123 |
+
):
|
| 124 |
+
"""
|
| 125 |
+
:param root: The root directory for this corpus.
|
| 126 |
+
:param fileids: a list or regexp specifying the fileids in this corpus.
|
| 127 |
+
:param word_tokenizer: tokenizer for breaking sentences or paragraphs
|
| 128 |
+
into words. Default: `WhitespaceTokenizer`
|
| 129 |
+
:param sent_tokenizer: tokenizer for breaking paragraphs into sentences.
|
| 130 |
+
:param encoding: the encoding that should be used to read the corpus.
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
CorpusReader.__init__(self, root, fileids, encoding)
|
| 134 |
+
self._word_tokenizer = word_tokenizer
|
| 135 |
+
self._sent_tokenizer = sent_tokenizer
|
| 136 |
+
self._readme = "README.txt"
|
| 137 |
+
|
| 138 |
+
def comparisons(self, fileids=None):
|
| 139 |
+
"""
|
| 140 |
+
Return all comparisons in the corpus.
|
| 141 |
+
|
| 142 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 143 |
+
comparisons have to be returned.
|
| 144 |
+
:return: the given file(s) as a list of Comparison objects.
|
| 145 |
+
:rtype: list(Comparison)
|
| 146 |
+
"""
|
| 147 |
+
if fileids is None:
|
| 148 |
+
fileids = self._fileids
|
| 149 |
+
elif isinstance(fileids, str):
|
| 150 |
+
fileids = [fileids]
|
| 151 |
+
return concat(
|
| 152 |
+
[
|
| 153 |
+
self.CorpusView(path, self._read_comparison_block, encoding=enc)
|
| 154 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 155 |
+
]
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def keywords(self, fileids=None):
|
| 159 |
+
"""
|
| 160 |
+
Return a set of all keywords used in the corpus.
|
| 161 |
+
|
| 162 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 163 |
+
keywords have to be returned.
|
| 164 |
+
:return: the set of keywords and comparative phrases used in the corpus.
|
| 165 |
+
:rtype: set(str)
|
| 166 |
+
"""
|
| 167 |
+
all_keywords = concat(
|
| 168 |
+
[
|
| 169 |
+
self.CorpusView(path, self._read_keyword_block, encoding=enc)
|
| 170 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 171 |
+
]
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
keywords_set = {keyword.lower() for keyword in all_keywords if keyword}
|
| 175 |
+
return keywords_set
|
| 176 |
+
|
| 177 |
+
def keywords_readme(self):
|
| 178 |
+
"""
|
| 179 |
+
Return the list of words and constituents considered as clues of a
|
| 180 |
+
comparison (from listOfkeywords.txt).
|
| 181 |
+
"""
|
| 182 |
+
keywords = []
|
| 183 |
+
with self.open("listOfkeywords.txt") as fp:
|
| 184 |
+
raw_text = fp.read()
|
| 185 |
+
for line in raw_text.split("\n"):
|
| 186 |
+
if not line or line.startswith("//"):
|
| 187 |
+
continue
|
| 188 |
+
keywords.append(line.strip())
|
| 189 |
+
return keywords
|
| 190 |
+
|
| 191 |
+
def sents(self, fileids=None):
|
| 192 |
+
"""
|
| 193 |
+
Return all sentences in the corpus.
|
| 194 |
+
|
| 195 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 196 |
+
sentences have to be returned.
|
| 197 |
+
:return: all sentences of the corpus as lists of tokens (or as plain
|
| 198 |
+
strings, if no word tokenizer is specified).
|
| 199 |
+
:rtype: list(list(str)) or list(str)
|
| 200 |
+
"""
|
| 201 |
+
return concat(
|
| 202 |
+
[
|
| 203 |
+
self.CorpusView(path, self._read_sent_block, encoding=enc)
|
| 204 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 205 |
+
]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
def words(self, fileids=None):
|
| 209 |
+
"""
|
| 210 |
+
Return all words and punctuation symbols in the corpus.
|
| 211 |
+
|
| 212 |
+
:param fileids: a list or regexp specifying the ids of the files whose
|
| 213 |
+
words have to be returned.
|
| 214 |
+
:return: the given file(s) as a list of words and punctuation symbols.
|
| 215 |
+
:rtype: list(str)
|
| 216 |
+
"""
|
| 217 |
+
return concat(
|
| 218 |
+
[
|
| 219 |
+
self.CorpusView(path, self._read_word_block, encoding=enc)
|
| 220 |
+
for (path, enc, fileid) in self.abspaths(fileids, True, True)
|
| 221 |
+
]
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
def _read_comparison_block(self, stream):
|
| 225 |
+
while True:
|
| 226 |
+
line = stream.readline()
|
| 227 |
+
if not line:
|
| 228 |
+
return [] # end of file.
|
| 229 |
+
comparison_tags = re.findall(COMPARISON, line)
|
| 230 |
+
if comparison_tags:
|
| 231 |
+
grad_comparisons = re.findall(GRAD_COMPARISON, line)
|
| 232 |
+
non_grad_comparisons = re.findall(NON_GRAD_COMPARISON, line)
|
| 233 |
+
# Advance to the next line (it contains the comparative sentence)
|
| 234 |
+
comparison_text = stream.readline().strip()
|
| 235 |
+
if self._word_tokenizer:
|
| 236 |
+
comparison_text = self._word_tokenizer.tokenize(comparison_text)
|
| 237 |
+
# Skip the next line (it contains closing comparison tags)
|
| 238 |
+
stream.readline()
|
| 239 |
+
# If gradable comparisons are found, create Comparison instances
|
| 240 |
+
# and populate their fields
|
| 241 |
+
comparison_bundle = []
|
| 242 |
+
if grad_comparisons:
|
| 243 |
+
# Each comparison tag has its own relations on a separate line
|
| 244 |
+
for comp in grad_comparisons:
|
| 245 |
+
comp_type = int(re.match(r"<cs-(\d)>", comp).group(1))
|
| 246 |
+
comparison = Comparison(
|
| 247 |
+
text=comparison_text, comp_type=comp_type
|
| 248 |
+
)
|
| 249 |
+
line = stream.readline()
|
| 250 |
+
entities_feats = ENTITIES_FEATS.findall(line)
|
| 251 |
+
if entities_feats:
|
| 252 |
+
for (code, entity_feat) in entities_feats:
|
| 253 |
+
if code == "1":
|
| 254 |
+
comparison.entity_1 = entity_feat.strip()
|
| 255 |
+
elif code == "2":
|
| 256 |
+
comparison.entity_2 = entity_feat.strip()
|
| 257 |
+
elif code == "3":
|
| 258 |
+
comparison.feature = entity_feat.strip()
|
| 259 |
+
keyword = KEYWORD.findall(line)
|
| 260 |
+
if keyword:
|
| 261 |
+
comparison.keyword = keyword[0]
|
| 262 |
+
comparison_bundle.append(comparison)
|
| 263 |
+
# If non-gradable comparisons are found, create a simple Comparison
|
| 264 |
+
# instance for each one
|
| 265 |
+
if non_grad_comparisons:
|
| 266 |
+
for comp in non_grad_comparisons:
|
| 267 |
+
# comp_type in this case should always be 4.
|
| 268 |
+
comp_type = int(re.match(r"<cs-(\d)>", comp).group(1))
|
| 269 |
+
comparison = Comparison(
|
| 270 |
+
text=comparison_text, comp_type=comp_type
|
| 271 |
+
)
|
| 272 |
+
comparison_bundle.append(comparison)
|
| 273 |
+
# Flatten the list of comparisons before returning them
|
| 274 |
+
# return concat([comparison_bundle])
|
| 275 |
+
return comparison_bundle
|
| 276 |
+
|
| 277 |
+
def _read_keyword_block(self, stream):
|
| 278 |
+
keywords = []
|
| 279 |
+
for comparison in self._read_comparison_block(stream):
|
| 280 |
+
keywords.append(comparison.keyword)
|
| 281 |
+
return keywords
|
| 282 |
+
|
| 283 |
+
def _read_sent_block(self, stream):
|
| 284 |
+
while True:
|
| 285 |
+
line = stream.readline()
|
| 286 |
+
if re.match(STARS, line):
|
| 287 |
+
while True:
|
| 288 |
+
line = stream.readline()
|
| 289 |
+
if re.match(STARS, line):
|
| 290 |
+
break
|
| 291 |
+
continue
|
| 292 |
+
if (
|
| 293 |
+
not re.findall(COMPARISON, line)
|
| 294 |
+
and not ENTITIES_FEATS.findall(line)
|
| 295 |
+
and not re.findall(CLOSE_COMPARISON, line)
|
| 296 |
+
):
|
| 297 |
+
if self._sent_tokenizer:
|
| 298 |
+
return [
|
| 299 |
+
self._word_tokenizer.tokenize(sent)
|
| 300 |
+
for sent in self._sent_tokenizer.tokenize(line)
|
| 301 |
+
]
|
| 302 |
+
else:
|
| 303 |
+
return [self._word_tokenizer.tokenize(line)]
|
| 304 |
+
|
| 305 |
+
def _read_word_block(self, stream):
|
| 306 |
+
words = []
|
| 307 |
+
for sent in self._read_sent_block(stream):
|
| 308 |
+
words.extend(sent)
|
| 309 |
+
return words
|