Description stringlengths 18 161k ⌀ | Code stringlengths 15 300k |
|---|---|
natural language toolkit word list corpus reader c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt this is a class to read the panlex swadesh list from david kamholz jonathan pool and susan m colowick 2014 panlex buildin... | import re
from collections import defaultdict, namedtuple
from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.corpus.reader.wordlist import WordListCorpusReader
from nltk.tokenize import line_tokenize
PanlexLanguage = namedtuple(
"PanlexLanguage",
[
"panlex_uid",
... |
natural language toolkit c 20012023 nltk project piotr kasprzyk p j kasprzykgmail com url https www nltk org for license information see license txt warning skip header to be implemented in the pl196x corpus each category is stored in single file and thus both methods provide identical functionality in order to accommo... | from nltk.corpus.reader.api import *
from nltk.corpus.reader.xmldocs import XMLCorpusReader
PARA = re.compile(r"<p(?: [^>]*){0,1}>(.*?)</p>")
SENT = re.compile(r"<s(?: [^>]*){0,1}>(.*?)</s>")
TAGGEDWORD = re.compile(r"<([wc](?: [^>]*){0,1}>)(.*?)</[wc]>")
WORD = re.compile(r"<[wc](?: [^>]*){0,1}>(.*?)</[wc]>")
TYPE ... |
natural language toolkit plaintext corpus reader c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com nitin madnani nmadnaniumiacs umd edu url https www nltk org for license information see license txt a reader for corpora that consist of plaintext documents reader for corpora that con... | import nltk.data
from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.tokenize import *
class PlaintextCorpusReader(CorpusReader):
CorpusView = StreamBackedCorpusView
def __init__(
self,
root,
fileids,
word_tokenizer=WordPunctTokenize... |
natural language toolkit pp attachment corpus reader c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt read lines from the prepositional phrase attachment corpus the pp attachment corpus contains several files having the... | from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
class PPAttachment:
def __init__(self, sent, verb, noun1, prep, noun2, attachment):
self.sent = sent
self.verb = verb
self.noun1 = noun1
self.prep = prep
self.noun2 = noun2
self.attachment = ... |
natural language toolkit pros and cons corpus reader c 20012023 nltk project pierpaolo pantone 24alsecondogmail com url https www nltk org for license information see license txt corpusreader for the pros and cons dataset pros and cons dataset information contact bing liu liubcs uic edu https www cs uic eduliub distrib... | import re
from nltk.corpus.reader.api import *
from nltk.tokenize import *
class ProsConsCorpusReader(CategorizedCorpusReader, CorpusReader):
CorpusView = StreamBackedCorpusView
def __init__(
self,
root,
fileids,
word_tokenizer=WordPunctTokenizer(),
encoding="ut... |
natural language toolkit rte corpus reader c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt corpus reader for the recognizing textual entailment rte challenge corpora the files were taken from the rte1 rte2 and rte3 datasets and the files were regularize... | from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.corpus.reader.xmldocs import *
def norm(value_string):
valdict = {"TRUE": 1, "FALSE": 0, "YES": 1, "NO": 0}
return valdict[value_string.upper()]
class RTEPair:
def __init__(
self,
pair,
... |
natural language toolkit semcor corpus reader c 20012023 nltk project nathan schneider nschneidcs cmu edu url https www nltk org for license information see license txt corpus reader for the semcor corpus corpus reader for the semcor corpus for access to the complete xml data structure use the xml method for access to ... | __docformat__ = "epytext en"
from nltk.corpus.reader.api import *
from nltk.corpus.reader.xmldocs import XMLCorpusReader, XMLCorpusView
from nltk.tree import Tree
class SemcorCorpusReader(XMLCorpusReader):
def __init__(self, root, fileids, wordnet, lazy=True):
XMLCorpusReader.__init__(self, root, f... |
natural language toolkit senseval 2 corpus reader c 20012023 nltk project trevor cohn tacohncs mu oz au steven bird stevenbird1gmail com modifications url https www nltk org for license information see license txt read from the senseval 2 corpus senseval http www senseval org evaluation exercises for word sense disambi... | import re
from xml.etree import ElementTree
from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.tokenize import *
class SensevalInstance:
def __init__(self, word, position, context, senses):
self.word = word
self.senses = tuple(senses)
self.position = posi... |
natural language toolkit string category corpus reader c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt read tuples from a corpus consisting of categorized strings for example from the question classification corpus num... | from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
class StringCategoryCorpusReader(CorpusReader):
def __init__(self, root, fileids, delimiter=" ", encoding="utf8"):
CorpusReader.__init__(self, root, fileids, encoding)
self._delimiter = delimiter
def tupl... |
natural language toolkit switchboard corpus reader c 20012023 nltk project edward loper edlopergmail com url https www nltk org for license information see license txt a specialized list object used to encode switchboard utterances the elements of the list are the words in the utterance and two attributes speaker and i... | import re
from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.tag import map_tag, str2tuple
class SwitchboardTurn(list):
def __init__(self, words, speaker, id):
list.__init__(self, words)
self.speaker = speaker
self.id = int(id)
def __repr__(sel... |
natural language toolkit tagged corpus reader c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com jacob perkins japerkgmail com url https www nltk org for license information see license txt a reader for corpora whose documents contain partofspeechtagged words reader for simple partof... | import os
from nltk.corpus.reader.api import *
from nltk.corpus.reader.timit import read_timit_block
from nltk.corpus.reader.util import *
from nltk.tag import map_tag, str2tuple
from nltk.tokenize import *
class TaggedCorpusReader(CorpusReader):
def __init__(
self,
root,
fileids,
... |
natural language toolkit timit corpus reader c 20012007 nltk project haejoong lee haejoongldc upenn edu steven bird stevenbird1gmail com jacob perkins japerkgmail com url https www nltk org for license information see license txt xx this docstring is outofdate read tokens phonemes and audio data from the nltk timit cor... | import sys
import time
from nltk.corpus.reader.api import *
from nltk.internals import import_from_stdlib
from nltk.tree import Tree
class TimitCorpusReader(CorpusReader):
_FILE_RE = r"(\w+-\w+/\w+\.(phn|txt|wav|wrd))|" + r"timitdic\.txt|spkrinfo\.txt"
_UTTERANCE_RE = r"\w+-\w+/\w+\.txt"
def ... |
natural language toolkit toolbox reader c 20012023 nltk project greg aumann gregaumannsil org stuart robinson stuart robinsonmpi nl steven bird stevenbird1gmail com url https www nltk org for license information see license txt module for reading writing and manipulating toolbox databases and settings fileids should pr... | from nltk.corpus.reader.api import *
from nltk.corpus.reader.util import *
from nltk.toolbox import ToolboxData
class ToolboxCorpusReader(CorpusReader):
def xml(self, fileids, key=None):
return concat(
[
ToolboxData(path, enc).parse(key=key)
for (path, enc) in s... |
natural language toolkit twitter corpus reader c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt a reader for corpora that consist of tweets it is assumed that the tweets have been serialised into linedelimited json corpusview streambackedcorpusview def i... | import json
import os
from nltk.corpus.reader.api import CorpusReader
from nltk.corpus.reader.util import StreamBackedCorpusView, ZipFilePathPointer, concat
from nltk.tokenize import TweetTokenizer
class TwitterCorpusReader(CorpusReader):
r
CorpusView = StreamBackedCorpusView
def __init__(
... |
udhr corpus reader it mostly deals with encodings the following files are not fully decodable because they were truncated at wrong bytes unfortunately encodings required for reading the following files are not supported by python the following files are encoded for specific fonts what are these the following files are ... | from nltk.corpus.reader.plaintext import PlaintextCorpusReader
from nltk.corpus.reader.util import find_corpus_fileids
class UdhrCorpusReader(PlaintextCorpusReader):
ENCODINGS = [
(".*-Latin1$", "latin-1"),
(".*-Hebrew$", "hebrew"),
(".*-Arabic$", "cp1256"),
("Czech_Cesky-UTF8", "... |
natural language toolkit verbnet corpus reader c 20012023 nltk project edward loper edlopergmail com url https www nltk org for license information see license txt an nltk interface to the verbnet verb lexicon for details about verbnet see https verbs colorado edumpalmerprojectsverbnet html an nltk interface to the ver... | import re
import textwrap
from collections import defaultdict
from nltk.corpus.reader.xmldocs import XMLCorpusReader
class VerbnetCorpusReader(XMLCorpusReader):
def __init__(self, root, fileids, wrap_etree=False):
XMLCorpusReader.__init__(self, root, fileids, wrap_etree)
self._lemma_t... |
natural language toolkit xml corpus reader c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt corpus reader for corpora whose documents are xml files note not named xml to avoid conflicting w standard xml package corpus reader for corpora whose docume... | import codecs
from xml.etree import ElementTree
from nltk.corpus.reader.api import CorpusReader
from nltk.corpus.reader.util import *
from nltk.data import SeekableUnicodeStreamReader
from nltk.internals import ElementWrapper
from nltk.tokenize import WordPunctTokenizer
class XMLCorpusReader(CorpusReader):
... |
natural language toolkit yorktorontohelsinki parsed corpus of old english prose ycoe c 20012015 nltk project selina dennis selinatranzfusion net url https www nltk org for license information see license txt corpus reader for the yorktorontohelsinki parsed corpus of old english prose ycoe a 1 5 million word syntactical... | import os
import re
from nltk.corpus.reader.api import *
from nltk.corpus.reader.bracket_parse import BracketParseCorpusReader
from nltk.corpus.reader.tagged import TaggedCorpusReader
from nltk.corpus.reader.util import *
from nltk.tokenize import RegexpTokenizer
class YCOECorpusReader(CorpusReader):
def _... |
natural language toolkit corpus reader utility functions c 20012023 nltk project edward loper edlopergmail com url https www nltk org for license information see license txt lazy corpus loader to see the api documentation for this lazily loaded corpus first run corpus ensureloaded and then run helpthiscorpus lazycorpus... | import gc
import re
import nltk
TRY_ZIPFILE_FIRST = False
class LazyCorpusLoader:
def __init__(self, name, reader_cls, *args, **kwargs):
from nltk.corpus.reader.api import CorpusReader
assert issubclass(reader_cls, CorpusReader)
self.__name = self.__name__ = name
self.__re... |
decorator module by michele simionato michelesimionatolibero it michele simionato distributed under the terms of the bsd license see below http www phyast pitt edumichelespythondocumentation html included in nltk for its support of a nice memoization decorator the basic trick is to generate the source code for the deco... | __docformat__ = "restructuredtext en"
__all__ = ["decorator", "new_wrapper", "getinfo"]
import sys
OLD_SYS_PATH = sys.path[:]
sys.path = [p for p in sys.path if p and "nltk" not in str(p)]
import inspect
sys.path = OLD_SYS_PATH
def __legacysignature(signature):
listsignature = str(signature)[1:-1]... |
natural language toolkit graphical representations package c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt import tkinterbased modules if tkinter is installed natural language toolkit graphical representations package ... | try:
import tkinter
except ImportError:
import warnings
warnings.warn("nltk.draw package not loaded (please install Tkinter library).")
else:
from nltk.draw.cfg import ProductionList, CFGEditor, CFGDemo
from nltk.draw.tree import (
TreeSegmentWidget,
tree_to_treesegment,
Tre... |
natural language toolkit dispersion plots c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt a utility for displaying lexical dispersion generate a lexical dispersion plot param text the source text type text liststr or iterstr param words the target ... | def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"):
try:
import matplotlib.pyplot as plt
except ImportError as e:
raise ImportError(
"The plot function requires matplotlib to be installed. "
"See https://matplotlib.org/"
) f... |
natural language toolkit nltk help c 20012023 nltk project s steven bird stevenbird1gmail com url https www nltk org for license information see license txt provide structured access to documentation utilities natural language toolkit nltk help c 2001 2023 nltk project s steven bird stevenbird1 gmail com url https www ... | import re
from textwrap import wrap
from nltk.data import load
def brown_tagset(tagpattern=None):
_format_tagset("brown_tagset", tagpattern)
def claws5_tagset(tagpattern=None):
_format_tagset("claws5_tagset", tagpattern)
def upenn_tagset(tagpattern=None):
_format_tagset("upenn_tagset", tagpattern)
... |
natural language toolkit inference c 20012023 nltk project dan garrette dhgarrettegmail com ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt classes and interfaces for theorem proving and model building natural language toolkit inference c 2001 2023 nltk project dan garrette dh... | from nltk.inference.api import ParallelProverBuilder, ParallelProverBuilderCommand
from nltk.inference.discourse import (
CfgReadingCommand,
DiscourseTester,
DrtGlueReadingCommand,
ReadingCommand,
)
from nltk.inference.mace import Mace, MaceCommand
from nltk.inference.prover9 import Prover9, Prover9Comm... |
natural language toolkit interface to the mace4 model builder dan garrette dhgarrettegmail com ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt a model builder that makes use of the external mace4 package a macecommand specific to the mace model builder it contains a printassum... | import os
import tempfile
from nltk.inference.api import BaseModelBuilderCommand, ModelBuilder
from nltk.inference.prover9 import Prover9CommandParent, Prover9Parent
from nltk.sem import Expression, Valuation
from nltk.sem.logic import is_indvar
class MaceCommand(Prover9CommandParent, BaseModelBuilderCommand):
... |
natural language toolkit nonmonotonic reasoning daniel h garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt a module to perform nonmonotonic reasoning the ideas and demonstrations in this module are based on logical foundations of artificial intelligence ... | from collections import defaultdict
from functools import reduce
from nltk.inference.api import Prover, ProverCommandDecorator
from nltk.inference.prover9 import Prover9, Prover9Command
from nltk.sem.logic import (
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
Boo... |
natural language toolkit interface to the prover9 theorem prover c 20012023 nltk project dan garrette dhgarrettegmail com ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt a theorem prover that makes use of the external prover9 package following is not yet used return code for 2... | import os
import subprocess
import nltk
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem.logic import (
AllExpression,
AndExpression,
EqualityExpression,
ExistsExpression,
Expression,
IffExpression,
ImpExpression,
NegatedExpression,
OrExpression,
)
p9_retur... |
natural language toolkit firstorder resolutionbased theorem prover dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt module for a resolutionbased first order theorem prover param goal input expression to prove type goal sem expression param assumptio... | import operator
from collections import defaultdict
from functools import reduce
from nltk.inference.api import BaseProverCommand, Prover
from nltk.sem import skolemize
from nltk.sem.logic import (
AndExpression,
ApplicationExpression,
EqualityExpression,
Expression,
IndividualVariableExpression,
... |
natural language toolkit firstorder tableau theorem prover c 20012023 nltk project dan garrette dhgarrettegmail com url https www nltk org for license information see license txt module for a tableaubased first order theorem prover if there s nothing left in the agenda and we haven t closed the path check if the branch... | from nltk.inference.api import BaseProverCommand, Prover
from nltk.internals import Counter
from nltk.sem.logic import (
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
EqualityExpression,
ExistsExpression,
Expression,
FunctionVariableExpression,
IffE... |
natural language toolkit internal utility functions c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com nitin madnani nmadnaniets org url https www nltk org for license information see license txt java via commandline xx add classpath option to configjava configure nltk s java interfa... | import fnmatch
import locale
import os
import re
import stat
import subprocess
import sys
import textwrap
import types
import warnings
from xml.etree import ElementTree
_java_bin = None
_java_options = []
def config_java(bin=None, options=None, verbose=False):
global _java_bin, _java_options
_java_bi... |
natural language toolkit json encoderdecoder helpers c 20012023 nltk project steven xu xxustudent unimelb edu au url https www nltk org for license information see license txt register json tags so the nltk data loader knows what module and class to look for nltk uses simple tags to mark the types of objects but the fu... | import json
json_tags = {}
TAG_PREFIX = "!"
def register_tag(cls):
json_tags[TAG_PREFIX + getattr(cls, "json_tag")] = cls
return cls
class JSONTaggedEncoder(json.JSONEncoder):
def default(self, obj):
obj_tag = getattr(obj, "json_tag", None)
if obj_tag is None:
return s... |
natural language toolkit language codes c 20222023 nltk project eric kafe kafe ericgmail com url https www nltk org for license information see license txt iso6393 language codes c https iso6393 sil org translate between language names and language codes the iso6393 language codes were downloaded from the registration ... | import re
from warnings import warn
from nltk.corpus import bcp47
codepattern = re.compile("[a-z][a-z][a-z]?")
def langname(tag, typ="full"):
tags = tag.split("-")
code = tags[0].lower()
if codepattern.fullmatch(code):
if code in iso639retired:
return iso639retired[code]
... |
this module is from mxdatetimelazymodule py and is distributed under the terms of the egenix com public license agreement https www egenix comproductsegenix compubliclicense1 1 0 pdf helper to enable simple lazy module import lazy means the actual import is deferred until an attribute is requested from the module s nam... | _debug = 0
class LazyModule:
__lazymodule_init = 0
__lazymodule_name = ""
__lazymodule_loaded = 0
__lazymodule_locals = None
__lazymodule_globals = None
def __init__(self, name, locals, globals=None):
self.__lazymodule_locals = locals
... |
natural language toolkit language models c 20012023 nltk project s ilia kurenkov ilia kurenkovgmail com url https www nltk org for license information see license txt nltk language modeling module currently this module covers only ngram language models but it should be easy to extend to neural models preparing data bef... | from nltk.lm.counter import NgramCounter
from nltk.lm.models import (
MLE,
AbsoluteDiscountingInterpolated,
KneserNeyInterpolated,
Laplace,
Lidstone,
StupidBackoff,
WittenBellInterpolated,
)
from nltk.lm.vocabulary import Vocabulary
__all__ = [
"Vocabulary",
"NgramCounter",
"MLE... |
natural language toolkit language models c 20012023 nltk project s ilia kurenkov ilia kurenkovgmail com url https www nltk org for license information see license txt language model interface import random import warnings from abc import abcmeta abstractmethod from bisect import bisect from itertools import accumulate ... | import random
import warnings
from abc import ABCMeta, abstractmethod
from bisect import bisect
from itertools import accumulate
from nltk.lm.counter import NgramCounter
from nltk.lm.util import log_base2
from nltk.lm.vocabulary import Vocabulary
class Smoothing(metaclass=ABCMeta):
def __init__(self, vocab... |
natural language toolkit c 20012023 nltk project ilia kurenkov ilia kurenkovgmail com url https www nltk org for license information see license txt language model counter class for counting ngrams will count any ngram sequence you give it first we need to make sure we are feeding the counter sentences of ngrams text a... | from collections import defaultdict
from collections.abc import Sequence
from nltk.probability import ConditionalFreqDist, FreqDist
class NgramCounter:
def __init__(self, ngram_text=None):
self._counts = defaultdict(ConditionalFreqDist)
self._counts[1] = self.unigrams = FreqDist()
... |
natural language toolkit language models c 20012023 nltk project ilia kurenkov ilia kurenkovgmail com manu joseph manujosephvgmail com url https www nltk org for license information see license txt language models from nltk lm api import languagemodel smoothing from nltk lm smoothing import absolutediscounting kneserne... | from nltk.lm.api import LanguageModel, Smoothing
from nltk.lm.smoothing import AbsoluteDiscounting, KneserNey, WittenBell
class MLE(LanguageModel):
def unmasked_score(self, word, context=None):
return self.context_counts(context).freq(word)
class Lidstone(LanguageModel):
def __i... |
natural language toolkit language model unit tests c 20012023 nltk project ilia kurenkov ilia kurenkovgmail com manu joseph manujosephvgmail com url https www nltk org for license information see license txt smoothing algorithms for language modeling according to chen goodman 1995 these should work with both backoff an... | from operator import methodcaller
from nltk.lm.api import Smoothing
from nltk.probability import ConditionalFreqDist
def _count_values_gt_zero(distribution):
as_count = (
methodcaller("N")
if isinstance(distribution, ConditionalFreqDist)
else lambda count: count
)
return... |
natural language toolkit c 20012023 nltk project ilia kurenkov ilia kurenkovgmail com url https www nltk org for license information see license txt language model utilities from math import log neginf floatinf posinf floatinf def logbase2score natural language toolkit c 2001 2023 nltk project ilia kurenkov ilia kurenk... | from math import log
NEG_INF = float("-inf")
POS_INF = float("inf")
def log_base2(score):
if score == 0.0:
return NEG_INF
return log(score, 2) |
natural language toolkit c 20012023 nltk project ilia kurenkov ilia kurenkovgmail com url https www nltk org for license information see license txt language model vocabulary import sys from collections import counter from collections abc import iterable from functools import singledispatch from itertools import chain ... | import sys
from collections import Counter
from collections.abc import Iterable
from functools import singledispatch
from itertools import chain
@singledispatch
def _dispatched_lookup(words, vocab):
raise TypeError(f"Unsupported type for looking up in vocabulary: {type(words)}")
@_dispatched_lookup.register(Ite... |
natural language toolkit metrics c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt nltk metrics classes and methods for scoring processing modules natural language toolkit metrics c 2001 2023 nltk project steven bird ste... | from nltk.metrics.agreement import AnnotationTask
from nltk.metrics.aline import align
from nltk.metrics.association import (
BigramAssocMeasures,
ContingencyMeasures,
NgramAssocMeasures,
QuadgramAssocMeasures,
TrigramAssocMeasures,
)
from nltk.metrics.confusionmatrix import ConfusionMatrix
from nlt... |
natural language toolkit agreement metrics c 20012023 nltk project tom lippincott tomcs columbia edu url https www nltk org for license information see license txt implementations of interannotator agreement coefficients surveyed by artstein and poesio 2007 intercoder agreement for computational linguistics an agreemen... | import logging
from itertools import groupby
from operator import itemgetter
from nltk.internals import deprecated
from nltk.metrics.distance import binary_distance
from nltk.probability import ConditionalFreqDist, FreqDist
log = logging.getLogger(__name__)
class AnnotationTask:
def __init__(self, data=No... |
natural language toolkit ngram association measures c 20012023 nltk project joel nothman jnothmanstudent usyd edu au url https www nltk org for license information see license txt provides scoring functions for a number of association measures through a generic abstract implementation in ngramassocmeasures and nspecifi... | import math as _math
from abc import ABCMeta, abstractmethod
from functools import reduce
_log2 = lambda x: _math.log2(x)
_ln = _math.log
_product = lambda s: reduce(lambda x, y: x * y, s)
_SMALL = 1e-20
try:
from scipy.stats import fisher_exact
except ImportError:
def fisher_exact(*_args, **_kwargs):
... |
natural language toolkit confusion matrices c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com tom aarsen url https www nltk org for license information see license txt the confusion matrix between a list of reference values and a corresponding list of test values entry r t of this m... | from nltk.probability import FreqDist
class ConfusionMatrix:
def __init__(self, reference, test, sort_by_count=False):
if len(reference) != len(test):
raise ValueError("Lists must have the same length.")
if sort_by_count:
ref_fdist = FreqDist(refere... |
natural language toolkit distance metrics c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com tom lippincott tomcs columbia edu url https www nltk org for license information see license txt distance metrics compute the distance between two items usually strings as metrics they must s... | import operator
import warnings
def _edit_dist_init(len1, len2):
lev = []
for i in range(len1):
lev.append([0] * len2)
for i in range(len1):
lev[i][0] = i
for j in range(len2):
lev[0][j] = j
return lev
def _last_left_t_init(sigma):
return {c: 0 for c in sigma}
... |
natural language toolkit agreement metrics c 20012023 nltk project lauri hallila laurihallilagmail com url https www nltk org for license information see license txt counts paice s performance statistics for evaluating stemming algorithms what is required a dictionary of words grouped by their real lemmas a dictionary ... | from math import sqrt
def get_words_from_dictionary(lemmas):
words = set()
for lemma in lemmas:
words.update(set(lemmas[lemma]))
return words
def _truncate(words, cutlength):
stems = {}
for word in words:
stem = word[:cutlength]
try:
stems[stem].upda... |
natural language toolkit evaluation c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt given a list of reference values and a corresponding list of test values return the fraction of corresponding values that are equal in... | import operator
from functools import reduce
from math import fabs
from random import shuffle
try:
from scipy.stats.stats import betai
except ImportError:
betai = None
from nltk.util import LazyConcatenation, LazyMap
def accuracy(reference, test):
if len(reference) != len(test):
raise Value... |
natural language toolkit text segmentation metrics c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com david doukhan david doukhangmail com url https www nltk org for license information see license txt text segmentation metrics 1 windowdiff pevzner l and hearst m a critique and impro... | try:
import numpy as np
except ImportError:
pass
def windowdiff(seg1, seg2, k, boundary="1", weighted=False):
if len(seg1) != len(seg2):
raise ValueError("Segmentations have unequal length")
if k > len(seg1):
raise ValueError(
"Window width k should be smaller or equa... |
natural language toolkit spearman rank correlation c 20012023 nltk project joel nothman jnothmanstudent usyd edu au url https www nltk org for license information see license txt tools for comparing ranked lists finds the difference between the values in ranks1 and ranks2 for keys present in both dicts if the arguments... | def _rank_dists(ranks1, ranks2):
ranks1 = dict(ranks1)
ranks2 = dict(ranks2)
for k in ranks1:
try:
yield k, ranks1[k] - ranks2[k]
except KeyError:
pass
def spearman_correlation(ranks1, ranks2):
n = 0
res = 0
for k, d in _rank_dists(ranks1, rank... |
natural language toolkit miscellaneous modules c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt natural language toolkit miscellaneous modules c 2001 2023 nltk project steven bird stevenbird1 gmail com url https www nltk org for license information ... | from nltk.misc.babelfish import babelize_shell
from nltk.misc.chomsky import generate_chomsky
from nltk.misc.minimalset import MinimalSet
from nltk.misc.wordfinder import word_finder |
this module previously provided an interface to babelfish online translation service this service is no longer available this module is kept in nltk source code in order to provide better error messages for people following the nltk book 2 0 | def babelize_shell():
print("Babelfish online translation service is no longer available.") |
natural language toolkit minimal sets c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt find contexts where more than one possible target value can appear e g if targets are wordinitial letters and contexts are the remainders of words then we would l... | from collections import defaultdict
class MinimalSet:
def __init__(self, parameters=None):
self._targets = set()
self._contexts = set()
self._seen = defaultdict(set)
self._displays = {}
if parameters:
for context, target, display in param... |
natural language toolkit list sorting c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt this module provides a variety of list sorting algorithms to illustrate the many different algorithms recipes for solving a problem and how to analyze algorithms ... | def selection(a):
count = 0
for i in range(len(a) - 1):
min = i
for j in range(i + 1, len(a)):
if a[j] < a[min]:
min = j
count += 1
a[min], a[i] = a[i], a[min]
return count
def bubble(a):
count = 0
for i in range(l... |
natural language toolkit word finder c 20012023 nltk project steven bird stevenbird1gmail com url https www nltk org for license information see license txt simplified from php version by robert klein brathnagmail com http fswordfinder sourceforge net reverse a word with probability 0 5 try to insert word at position x... | import random
def revword(word):
if random.randint(1, 2) == 1:
return word[::-1]
return word
def step(word, x, xf, y, yf, grid):
for i in range(len(word)):
if grid[xf(i)][yf(i)] != "" and grid[xf(i)][yf(i)] != word[i]:
return False
for i in range(len(word)):
gri... |
natural language toolkit parsers c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt nltk parsers classes and interfaces for producing tree structures that represent the internal organization of a text this task is known a... | from nltk.parse.api import ParserI
from nltk.parse.bllip import BllipParser
from nltk.parse.chart import (
BottomUpChartParser,
BottomUpLeftCornerChartParser,
ChartParser,
LeftCornerChartParser,
SteppingChartParser,
TopDownChartParser,
)
from nltk.parse.corenlp import CoreNLPDependencyParser, Co... |
natural language toolkit parser api c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt a processing class for deriving trees that represent possible structures for a sequence of tokens these tree structures are known as p... | import itertools
from nltk.internals import overridden
class ParserI:
def grammar(self):
raise NotImplementedError()
def parse(self, sent, *args, **kwargs):
if overridden(self.parse_sents):
return next(self.parse_sents([sent], *args, **kwargs))
eli... |
natural language toolkit an incremental earley chart parser c 20012023 nltk project peter ljunglf peter ljunglofheatherleaf se rob speer rspeermit edu edward loper edlopergmail com steven bird stevenbird1gmail com jean mark gawron gawronmail sdsu edu url https www nltk org for license information see license txt data c... | from time import perf_counter
from nltk.parse.chart import (
BottomUpPredictCombineRule,
BottomUpPredictRule,
CachedTopDownPredictRule,
Chart,
ChartParser,
EdgeI,
EmptyPredictRule,
FilteredBottomUpPredictCombineRule,
FilteredSingleEdgeFundamentalRule,
LeafEdge,
LeafInitRule,... |
natural language toolkit chart parser for featurebased grammars c 20012023 nltk project rob speer rspeermit edu peter ljunglf peter ljunglofheatherleaf se url https www nltk org for license information see license txt extension of chart parsing implementation to handle grammars with feature structures as nodes tree edg... | from time import perf_counter
from nltk.featstruct import TYPE, FeatStruct, find_variables, unify
from nltk.grammar import (
CFG,
FeatStructNonterminal,
Nonterminal,
Production,
is_nonterminal,
is_terminal,
)
from nltk.parse.chart import (
BottomUpPredictCombineRule,
BottomUpPredictRule... |
natural language toolkit interface to maltparser dan garrette dhgarrettegmail com contributor liling tan mustufain osamamukhtar11 c 20012023 nltk project url https www nltk org for license information see license txt a module to find maltparser jar file and its dependencies checks that that the found directory contains... | import inspect
import os
import subprocess
import sys
import tempfile
from nltk.data import ZipFilePathPointer
from nltk.internals import find_dir, find_file, find_jars_within_path
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
from nltk.parse.util import taggedsents_to_conll... |
natural language toolkit dependency grammars c 20012023 nltk project jason narad jason naradgmail com url https www nltk org for license information see license txt dependencyscoreri interface for graphedge weight calculation a scorer for calculated the weights on the edges of a weighted dependency graph this is used b... | import logging
import math
from nltk.parse.dependencygraph import DependencyGraph
logger = logging.getLogger(__name__)
class DependencyScorerI:
def __init__(self):
if self.__class__ == DependencyScorerI:
raise TypeError("DependencyScorerI is an abstract interface")
def train(s... |
natural language toolkit recursive descent parser c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt recursive descent parser a simple topdown cfg parser that parses texts by recursively expanding the fringe of a tree and... | from nltk.grammar import Nonterminal
from nltk.parse.api import ParserI
from nltk.tree import ImmutableTree, Tree
class RecursiveDescentParser(ParserI):
def __init__(self, grammar, trace=0):
self._grammar = grammar
self._trace = trace
def grammar(self):
return self._... |
natural language toolkit shiftreduce parser c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt shiftreduce parser a simple bottomup cfg parser that uses two operations shift and reduce to find a single parse for a text sh... | from nltk.grammar import Nonterminal
from nltk.parse.api import ParserI
from nltk.tree import Tree
class ShiftReduceParser(ParserI):
def __init__(self, grammar, trace=0):
self._grammar = grammar
self._trace = trace
self._check_grammar()
def grammar(self):
ret... |
natural language toolkit interface to the stanford parser c 20012023 nltk project steven xu xxustudent unimelb edu au url https www nltk org for license information see license txt interface to the stanford parser modeljarpattern rstanfordparserd dmodels jar jar rstanfordparser jar mainclass edu stanford nlp parser lex... | import os
import tempfile
import warnings
from subprocess import PIPE
from nltk.internals import (
_java_options,
config_java,
find_jar_iter,
find_jars_within_path,
java,
)
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
from nltk.tree import Tree
_stanfor... |
natural language toolkit semantic interpretation c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt nltk semantic interpretation package this package contains classes for representing semantic structure in formulas of firstorder logic and for evaluating su... | from nltk.sem.boxer import Boxer
from nltk.sem.drt import DRS, DrtExpression
from nltk.sem.evaluate import (
Assignment,
Model,
Undefined,
Valuation,
arity,
is_rel,
read_valuation,
set2rel,
)
from nltk.sem.lfg import FStructure
from nltk.sem.logic import (
ApplicationExpression,
... |
natural language toolkit interface to boxer http svn ask it usyd edu autraccandcwikiboxer dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt an interface to boxer this interface relies on the latest version of the development subversion version of cc ... | import operator
import os
import re
import subprocess
import tempfile
from functools import reduce
from optparse import OptionParser
from nltk.internals import find_binary
from nltk.sem.drt import (
DRS,
DrtApplicationExpression,
DrtEqualityExpression,
DrtNegatedExpression,
DrtOrExpression,
Drt... |
natural language toolkit cooper storage for quantifier ambiguity c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt a container for handling quantifier ambiguity via cooper storage param featstruct the value of the sem node in a tree from parsewithbindops ... | from nltk.parse import load_parser
from nltk.parse.featurechart import InstantiateVarsChart
from nltk.sem.logic import ApplicationExpression, LambdaExpression, Variable
class CooperStore:
def __init__(self, featstruct):
self.featstruct = featstruct
self.readings = []
try:
... |
natural language toolkit discourse representation theory drt dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt import tkinterbased modules if they are available no need to print a warning here nltk draw has already printed one a lambda calculus expre... | import operator
from functools import reduce
from itertools import chain
from nltk.sem.logic import (
APP,
AbstractVariableExpression,
AllExpression,
AndExpression,
ApplicationExpression,
BinaryExpression,
BooleanExpression,
ConstantExpression,
EqualityExpression,
EventVariableE... |
natural language toolkit logic peter wang updated by dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt an implementation of the hole semantics model following blackburn and bos representation and inference for natural language csli 2005 the semantic ... | from functools import reduce
from nltk.parse import load_parser
from nltk.sem.logic import (
AllExpression,
AndExpression,
ApplicationExpression,
ExistsExpression,
IffExpression,
ImpExpression,
LambdaExpression,
NegatedExpression,
OrExpression,
)
from nltk.sem.skolemize import skole... |
natural language toolkit lexical functional grammar dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt append item to the list at key if no list exists for key then construct one add all the dependencies for all the nodes the value of a spec entry is ... | from itertools import chain
from nltk.internals import Counter
class FStructure(dict):
def safeappend(self, key, item):
if key not in self:
self[key] = []
self[key].append(item)
def __setitem__(self, key, value):
dict.__setitem__(self, key.lower(), value)
de... |
natural language toolkit linear logic dan garrette dhgarrettegmail com c 20012023 nltk project url https www nltk org for license information see license txt punctuation operations a linear logic expression parser def initself logicparser initself self operatorprecedence app 1 tokens imp 2 none 3 self rightassociatedop... | from nltk.internals import Counter
from nltk.sem.logic import APP, LogicParser
_counter = Counter()
class Tokens:
OPEN = "("
CLOSE = ")"
IMP = "-o"
PUNCT = [OPEN, CLOSE]
TOKENS = PUNCT + [IMP]
class LinearLogicParser(LogicParser):
def __init__(self):
LogicParser.__... |
natural language toolkit semantic interpretation ewan klein ewaninf ed ac uk c 20012023 nltk project url https www nltk org for license information see license txt skolemize the expression and convert to conjunctive normal form cnf convert this split disjunction to conjunctive normal form cnf natural language toolkit s... | from nltk.sem.logic import (
AllExpression,
AndExpression,
ApplicationExpression,
EqualityExpression,
ExistsExpression,
IffExpression,
ImpExpression,
NegatedExpression,
OrExpression,
VariableExpression,
skolem_function,
unique_variable,
)
def skolemize(expression, univ_... |
natural language toolkit sentiment analysis c 20012023 nltk project ewan klein ewaninf ed ac uk url https www nltk org for license information see license txt nltk sentiment analysis package natural language toolkit sentiment analysis c 2001 2023 nltk project ewan klein ewan inf ed ac uk url https www nltk org for lice... | from nltk.sentiment.sentiment_analyzer import SentimentAnalyzer
from nltk.sentiment.vader import SentimentIntensityAnalyzer |
natural language toolkit sentiment analyzer c 20012023 nltk project pierpaolo pantone 24alsecondogmail com url https www nltk org for license information see license txt a sentimentanalyzer is a tool to implement and facilitate sentiment analysis tasks using nltk features and classifiers especially for teaching and dem... | import sys
from collections import defaultdict
from nltk.classify.util import accuracy as eval_accuracy
from nltk.classify.util import apply_features
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
from nltk.metrics import f_measure as eval_f_measure
from nltk.metrics... |
natural language toolkit sentiment analyzer c 20012023 nltk project pierpaolo pantone 24alsecondogmail com url https www nltk org for license information see license txt utility methods for sentiment analysis regular expressions regular expression for negation by christopher potts happy and sad emoticons a timer decora... | import codecs
import csv
import json
import pickle
import random
import re
import sys
import time
from copy import deepcopy
import nltk
from nltk.corpus import CategorizedPlaintextCorpusReader
from nltk.data import load
from nltk.tokenize.casual import EMOTICON_RE
NEGATION = r
NEGATION_RE = re.compile(NEGATION,... |
natural language toolkit vader c 20012023 nltk project c j hutto clayton huttogtri gatech edu ewan klein ewaninf ed ac uk modifications pierpaolo pantone 24alsecondogmail com modifications george berry geb97cornell edu modifications malavika suresh malavika suresh0794gmail com modifications url https www nltk org for l... | import math
import re
import string
from itertools import product
import nltk.data
from nltk.util import pairwise
class VaderConstants:
B_INCR = 0.293
B_DECR = -0.293
C_INCR = 0.733
N_SCALAR = -0.74
NEGATE = {
"aint",
"arent",
"cannot",
... |
natural language toolkit stemmers c 20012023 nltk project trevor cohn tacohncs mu oz au edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt nltk stemmers interfaces used to remove morphological affixes from words leaving only the word stem stemmi... | from nltk.stem.api import StemmerI
from nltk.stem.arlstem import ARLSTem
from nltk.stem.arlstem2 import ARLSTem2
from nltk.stem.cistem import Cistem
from nltk.stem.isri import ISRIStemmer
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem.porter import PorterStemmer
from nltk.stem.regexp import RegexpStemm... |
natural language toolkit arlstem stemmer c 20012023 nltk project kheireddine abainia xprogramer k abainiagmail com algorithms kheireddine abainia k abainiagmail com siham ouamour halim sayoud url https www nltk org for license information see license txt arlstem arabic stemmer the details about the implementation of th... | import re
from nltk.stem.api import StemmerI
class ARLSTem(StemmerI):
def __init__(self):
self.re_hamzated_alif = re.compile(r"[\u0622\u0623\u0625]")
self.re_alifMaqsura = re.compile(r"[\u0649]")
self.re_diacritics = re.compile(r"[\u064B-\u065F]")
self.pr2... |
natural language toolkit arlstem stemmer v2 c 20012023 nltk project kheireddine abainia xprogramer k abainiagmail com algorithms kheireddine abainia k abainiagmail com hamza rebbani hamrebbanigmail com url https www nltk org for license information see license txt arlstem2 arabic light stemmer the details about the imp... | import re
from nltk.stem.api import StemmerI
class ARLSTem2(StemmerI):
def __init__(self):
self.re_hamzated_alif = re.compile(r"[\u0622\u0623\u0625]")
self.re_alifMaqsura = re.compile(r"[\u0649]")
self.re_diacritics = re.compile(r"[\u064B-\u065F]")
self.pr... |
natural language toolkit cistem stemmer for german c 20012023 nltk project leonie weissweiler l weissweileroutlook de tom aarsen modifications algorithm leonie weissweiler l weissweileroutlook de alexander fraser frasercis lmu de url https www nltk org for license information see license txt cistem stemmer for german t... | import re
from typing import Tuple
from nltk.stem.api import StemmerI
class Cistem(StemmerI):
strip_ge = re.compile(r"^ge(.{4,})")
repl_xx = re.compile(r"(.)\1")
strip_emr = re.compile(r"e[mr]$")
strip_nd = re.compile(r"nd$")
strip_t = re.compile(r"t$")
strip_esn = re.compile(r"[esn]$")... |
natural language toolkit the isri arabic stemmer c 20012023 nltk project algorithm kazem taghva rania elkhoury and jeffrey coombs 2005 hosam algasaier hosamhmeyahoo com url https www nltk org for license information see license txt isri arabic stemmer the algorithm for this stemmer is described in taghva k elkoury r an... | import re
from nltk.stem.api import StemmerI
class ISRIStemmer(StemmerI):
def __init__(self):
self.p3 = [
"\u0643\u0627\u0644",
"\u0628\u0627\u0644",
"\u0648\u0644\u0644",
"\u0648\u0627\u0644",
]
self.p2 = ["\u0627\u... |
natural language toolkit stemmers c 20012023 nltk project steven tomcavage stomcavalaw upenn edu url https www nltk org for license information see license txt a word stemmer based on the lancaster paicehusk stemming algorithm paice chris d another stemmer acm sigir forum 24 3 1990 5661 lancaster stemmer from nltk stem... | import re
from nltk.stem.api import StemmerI
class LancasterStemmer(StemmerI):
default_rule_tuple = (
"ai*2.",
"a*1.",
"bb1.",
"city3s.",
"ci2>",
"cn1t>",
"dd1.",
"dei3y>",
"deec2ss.",
"dee1.",
... |
porter stemmer this is the porter stemming algorithm it follows the algorithm presented in porter m an algorithm for suffix stripping program 14 3 1980 130137 with some optional deviations that can be turned on or off with the mode argument to the constructor martin porter the algorithm s inventor maintains a web page ... | __docformat__ = "plaintext"
import re
from nltk.stem.api import StemmerI
class PorterStemmer(StemmerI):
NLTK_EXTENSIONS = "NLTK_EXTENSIONS"
MARTIN_EXTENSIONS = "MARTIN_EXTENSIONS"
ORIGINAL_ALGORITHM = "ORIGINAL_ALGORITHM"
def __init__(self, mode=NLTK_EXTENSIONS):
if mode not in (... |
natural language toolkit stemmers c 20012023 nltk project trevor cohn tacohncs mu oz au edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt a stemmer that uses regular expressions to identify morphological affixes any substrings that match the re... | import re
from nltk.stem.api import StemmerI
class RegexpStemmer(StemmerI):
def __init__(self, regexp, min=0):
if not hasattr(regexp, "pattern"):
regexp = re.compile(regexp)
self._regexp = regexp
self._min = min
def stem(self, word):
if len(word) < self._mi... |
natural language toolkit snowball stemmer c 20012023 nltk project peter michael stahl pemistahlgmail com peter ljunglof peter ljunglofheatherleaf se revisions lakhdar benzahia lakhdar benzahiagmail com cowriter assem chelli assem chgmail com reviewer arabicstemmer abdelkrim aries abariesesi dz reviewer arabicstemmer al... | import re
from nltk.corpus import stopwords
from nltk.stem import porter
from nltk.stem.api import StemmerI
from nltk.stem.util import prefix_replace, suffix_replace
class SnowballStemmer(StemmerI):
languages = (
"arabic",
"danish",
"dutch",
"english",
"finnish",
... |
natural language toolkit stemmer utilities c 20012023 nltk project helder he7d3rgmail com url https www nltk org for license information see license txt replaces the old suffix of the original string by a new suffix replaces the old prefix of the original string by a new suffix param original string param old string pa... | def suffix_replace(original, old, new):
return original[: -len(old)] + new
def prefix_replace(original, old, new):
return new + original[len(old) :] |
natural language toolkit wordnet stemmer interface c 20012023 nltk project steven bird stevenbird1gmail com edward loper edlopergmail com url https www nltk org for license information see license txt wordnet lemmatizer lemmatize using wordnet s builtin morphy function returns the input word unchanged if it cannot be f... | from nltk.corpus import wordnet as wn
class WordNetLemmatizer:
def lemmatize(self, word: str, pos: str = "n") -> str:
lemmas = wn._morphy(word, pos)
return min(lemmas, key=len) if lemmas else word
def __repr__(self):
return "<WordNetLemmatizer>" |
natural language toolkit taggers c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com minor additions url https www nltk org for license information see license txt nltk taggers this package contains classes and interfaces for partofspeech tagging or simply tagging a tag is a casesensi... | from nltk.tag.api import TaggerI
from nltk.tag.util import str2tuple, tuple2str, untag
from nltk.tag.sequential import (
SequentialBackoffTagger,
ContextTagger,
DefaultTagger,
NgramTagger,
UnigramTagger,
BigramTagger,
TrigramTagger,
AffixTagger,
RegexpTagger,
ClassifierBasedTagge... |
natural language toolkit interface to the crfsuite tagger c 20012023 nltk project long duong longdt219gmail com url https www nltk org for license information see license txt a module for pos tagging using crfsuite a module for pos tagging using crfsuite https pypi python orgpypipythoncrfsuite from nltk tag import crft... | import re
import unicodedata
from nltk.tag.api import TaggerI
try:
import pycrfsuite
except ImportError:
pass
class CRFTagger(TaggerI):
def __init__(self, feature_func=None, verbose=False, training_opt={}):
self._model_file = ""
self._tagger = pycrfsuite.Tagger()
... |
natural language toolkit hidden markov model c 20012023 nltk project trevor cohn tacohncsse unimelb edu au philip blunsom pcblcsse unimelb edu au tiago tresoldi tiagotresoldi pro br fixes steven bird stevenbird1gmail com fixes joseph frazee jfrazeemail utexas edu fixes steven xu xxustudent unimelb edu au fixes url http... | import itertools
import re
try:
import numpy as np
except ImportError:
pass
from nltk.metrics import accuracy
from nltk.probability import (
ConditionalFreqDist,
ConditionalProbDist,
DictionaryConditionalProbDist,
DictionaryProbDist,
FreqDist,
LidstoneProbDist,
MLEProbDist,
Mut... |
natural language toolkit interface to the hunpos postagger c 20012023 nltk project peter ljunglf peter ljunglofheatherleaf se dvid mrk nemeskey nemeskeydgmail com modifications attila zsder zsedergmail com modifications url https www nltk org for license information see license txt a module for interfacing with the hun... | import os
from subprocess import PIPE, Popen
from nltk.internals import find_binary, find_file
from nltk.tag.api import TaggerI
_hunpos_url = "https://code.google.com/p/hunpos/"
_hunpos_charset = "ISO-8859-1"
class HunposTagger(TaggerI):
def __init__(
self, path_to_model, path_to_bin=None, encod... |
natural language toolkit tagset mapping c 20012023 nltk project nathan schneider nathancmu edu steven bird stevenbird1gmail com url https www nltk org for license information see license txt interface for converting pos tags from various treebanks to the universal tagset of petrov das mcdonald the tagset consists of th... | from collections import defaultdict
from os.path import join
from nltk.data import load
_UNIVERSAL_DATA = "taggers/universal_tagset"
_UNIVERSAL_TAGS = (
"VERB",
"NOUN",
"PRON",
"ADJ",
"ADV",
"ADP",
"CONJ",
"DET",
"NUM",
"PRT",
"X",
".",
)
_MAPPINGS = defaultdict(lamb... |
this module is a port of the textblob averaged perceptron tagger matthew honnibal honnibalghgmail com long duong longdt219gmail com nltk port url https github comsloriatextblobaptagger https www nltk org 2013 matthew honnibal nltk modifications 2015 the nltk project this module is provided under the terms of the mit li... | import logging
import pickle
import random
from collections import defaultdict
from nltk import jsontags
from nltk.data import find, load
from nltk.tag.api import TaggerI
try:
import numpy as np
except ImportError:
pass
PICKLE = "averaged_perceptron_tagger.pickle"
@jsontags.register_tag
class AveragedPerce... |
natural language toolkit senna pos tagger c 20012023 nltk project rami alrfou ralrfoucs stonybrook edu url https www nltk org for license information see license txt senna pos tagger ner tagger chunk tagger the input is path to the directory that contains senna executables if the path is incorrect sennatagger will auto... | from nltk.classify import Senna
class SennaTagger(Senna):
def __init__(self, path, encoding="utf-8"):
super().__init__(path, ["pos"], encoding)
def tag_sents(self, sentences):
tagged_sents = super().tag_sents(sentences)
for i in range(len(tagged_sents)):
for j in ... |
natural language toolkit tnt tagger c 20012023 nltk project sam huston sjh900gmail com url https www nltk org for license information see license txt implementation of tnt a statisical part of speech tagger by thorsten brants https aclanthology orga001031 pdf tnt statistical pos tagger important notes does not automati... | from math import log
from operator import itemgetter
from nltk.probability import ConditionalFreqDist, FreqDist
from nltk.tag.api import TaggerI
class TnT(TaggerI):
def __init__(self, unk=None, Trained=False, N=1000, C=False):
self._uni = FreqDist()
self._bi = ConditionalFreqDist(... |
natural language toolkit tagger utilities c 20012023 nltk project edward loper edlopergmail com steven bird stevenbird1gmail com url https www nltk org for license information see license txt given the string representation of a tagged token return the corresponding tuple representation the rightmost occurrence of sep ... | def str2tuple(s, sep="/"):
loc = s.rfind(sep)
if loc >= 0:
return (s[:loc], s[loc + len(sep) :].upper())
else:
return (s, None)
def tuple2str(tagged_token, sep="/"):
word, tag = tagged_token
if tag is None:
return word
else:
assert sep not in tag, "tag... |
natural language toolkit transformationbased learning c 20012023 nltk project marcus uneson marcus unesongmail com based on previous nltk2 version by christopher maloof edward loper steven bird url https www nltk org for license information see license txt transformation based learning a general purpose package for tra... | from nltk.tbl.template import Template
from nltk.tbl.feature import Feature
from nltk.tbl.rule import Rule
from nltk.tbl.erroranalysis import error_list |
natural language toolkit transformationbased learning c 20012023 nltk project marcus uneson marcus unesongmail com based on previous nltk2 version by christopher maloof edward loper steven bird url https www nltk org for license information see license txt run a demo with defaults see source comments for details or doc... | import os
import pickle
import random
import time
from nltk.corpus import treebank
from nltk.tag import BrillTaggerTrainer, RegexpTagger, UnigramTagger
from nltk.tag.brill import Pos, Word
from nltk.tbl import Template, error_list
def demo():
postag()
def demo_repr_rule_format():
postag(ruleforma... |
natural language toolkit transformationbased learning c 20012023 nltk project marcus uneson marcus unesongmail com based on previous nltk2 version by christopher maloof edward loper steven bird url https www nltk org for license information see license txt returns a list of errors in string format returns a list of hum... | def error_list(train_sents, test_sents):
hdr = ("%25s | %s | %s\n" + "-" * 26 + "+" + "-" * 24 + "+" + "-" * 26) % (
"left context",
"word/test->gold".center(22),
"right context",
)
errors = [hdr]
for (train_sent, test_sent) in zip(train_sents, test_sents):
for wordn... |
test suite that runs all nltk tests this module nltk test all is named as the nltk testsuite in the project s setupeggs py file here we create a test suite that runs all of our doctests and return it for processing by the setuptools test harness printhere000000000000000 print globos path joinos path dirnamefile doctest... | import doctest
import os.path
import unittest
from glob import glob
def additional_tests():
dir = os.path.dirname(__file__)
paths = glob(os.path.join(dir, "*.doctest"))
files = [os.path.basename(path) for path in paths]
return unittest.TestSuite([doctest.DocFileSuite(file) for file in files]... |
most of classify doctest requires numpy most of classify doctest requires numpy | def setup_module():
import pytest
pytest.importorskip("numpy") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.