id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
170,610 | import math
from itertools import islice
from nltk.util import choose, ngrams
def sentence_ribes(references, hypothesis, alpha=0.25, beta=0.10):
"""
The RIBES (Rank-based Intuitive Bilingual Evaluation Score) from
Hideki Isozaki, Tsutomu Hirao, Kevin Duh, Katsuhito Sudoh and
Hajime Tsukada. 2010. "Autom... | This function "calculates RIBES for a system output (hypothesis) with multiple references, and returns "best" score among multi-references and individual scores. The scores are corpus-wise, i.e., averaged by the number of sentences." (c.f. RIBES version 1.03.1 code). Different from BLEU's micro-average precision, RIBES... |
170,611 | import math
from itertools import islice
from nltk.util import choose, ngrams
def choose(n, k):
"""
This function is a fast way to calculate binomial coefficients, commonly
known as nCk, i.e. the number of combinations of n things taken k at a time.
(https://en.wikipedia.org/wiki/Binomial_coefficient).... | Calculates the Spearman's Rho correlation coefficient given the *worder* list of word alignment from word_rank_alignment(), using the formula: rho = 1 - sum(d**2) / choose(len(worder)+1, 3) Given that d is the sum of difference between the *worder* list of indices and the original word indices from the reference senten... |
170,612 | import math
import sys
import warnings
from collections import Counter
from fractions import Fraction
from nltk.util import ngrams
def corpus_bleu(
list_of_references,
hypotheses,
weights=(0.25, 0.25, 0.25, 0.25),
smoothing_function=None,
auto_reweigh=False,
):
"""
Calculate a single corpus-... | Calculate BLEU score (Bilingual Evaluation Understudy) from Papineni, Kishore, Salim Roukos, Todd Ward, and Wei-Jing Zhu. 2002. "BLEU: a method for automatic evaluation of machine translation." In Proceedings of ACL. https://www.aclweb.org/anthology/P02-1040.pdf >>> hypothesis1 = ['It', 'is', 'a', 'guide', 'to', 'actio... |
170,613 | import fractions
import math
from collections import Counter
from nltk.util import ngrams
def corpus_nist(list_of_references, hypotheses, n=5):
"""
Calculate a single corpus-level NIST score (aka. system-level BLEU) for all
the hypotheses and their respective references.
:param references: a corpus of l... | Calculate NIST score from George Doddington. 2002. "Automatic evaluation of machine translation quality using n-gram co-occurrence statistics." Proceedings of HLT. Morgan Kaufmann Publishers Inc. https://dl.acm.org/citation.cfm?id=1289189.1289273 DARPA commissioned NIST to develop an MT evaluation facility based on the... |
170,614 | from collections import defaultdict
class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]):
default_factory: Callable[[], _VT]
def __init__(self, **kwargs: _VT) -> None: ...
def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ...
def __init__(self, default_factory: Optional[Callable... | This module symmetrisatizes the source-to-target and target-to-source word alignment output and produces, aka. GDFA algorithm (Koehn, 2005). Step 1: Find the intersection of the bidirectional alignment. Step 2: Search for additional neighbor alignment points to be added, given these criteria: (i) neighbor alignments po... |
170,615 | import math
class LanguageIndependent:
# These are the language-independent probabilities and parameters
# given in Gale & Church
# for the computation, l_1 is always the language with less characters
PRIORS = {
(1, 0): 0.0099,
(0, 1): 0.0099,
(1, 1): 0.89,
(2, 1): 0.089,... | Creates the sentence alignment of two texts. Texts can consist of several blocks. Block boundaries cannot be crossed by sentence alignment links. Each block consists of a list that contains the lengths (in characters) of the sentences in this block. @param source_blocks: The list of blocks in the source text. @param ta... |
170,616 | import math
def split_at(it, split_value):
"""Splits an iterator C{it} at values of C{split_value}.
Each instance of C{split_value} is swallowed. The iterator produces
subiterators which need to be consumed fully before the next subiterator
can be used.
"""
def _chunk_iterator(first):
v ... | Parses a stream of tokens and splits it into sentences (using C{soft_delimiter} tokens) and blocks (using C{hard_delimiter} tokens) for use with the L{align_texts} function. |
170,617 | import re
from collections import Counter, defaultdict
from nltk.util import ngrams
def corpus_chrf(
references, hypotheses, min_len=1, max_len=6, beta=3.0, ignore_whitespace=True
):
"""
Calculates the corpus level CHRF (Character n-gram F-score), it is the
macro-averaged value of the sentence/segment l... | Calculates the sentence level CHRF (Character n-gram F-score) described in - Maja Popovic. 2015. CHRF: Character n-gram F-score for Automatic MT Evaluation. In Proceedings of the 10th Workshop on Machine Translation. https://www.statmt.org/wmt15/pdf/WMT49.pdf - Maja Popovic. 2016. CHRF Deconstructed: β Parameters and n... |
170,618 |
The provided code snippet includes necessary dependencies for implementing the `alignment_error_rate` function. Write a Python function `def alignment_error_rate(reference, hypothesis, possible=None)` to solve the following problem:
Return the Alignment Error Rate (AER) of an alignment with respect to a "gold standar... | Return the Alignment Error Rate (AER) of an alignment with respect to a "gold standard" reference alignment. Return an error rate between 0.0 (perfect alignment) and 1.0 (no alignment). >>> from nltk.translate import Alignment >>> ref = Alignment([(0, 0), (1, 1), (2, 2)]) >>> test = Alignment([(0, 0), (1, 2), (2, 1)]) ... |
170,619 | from functools import reduce
from nltk.parse.api import ParserI
from nltk.tree import ProbabilisticTree, Tree
class ViterbiParser(ParserI):
"""
A bottom-up ``PCFG`` parser that uses dynamic programming to find
the single most likely parse for a text. The ``ViterbiParser`` parser
parses texts by filling... | A demonstration of the probabilistic parsers. The user is prompted to select which demo to run, and how many parses should be found; and then each parser is run on the same demo, and a summary of the results are displayed. |
170,620 | from nltk.data import load
from nltk.grammar import CFG, PCFG, FeatureGrammar
from nltk.parse.chart import Chart, ChartParser
from nltk.parse.featurechart import FeatureChart, FeatureChartParser
from nltk.parse.pchart import InsideChartParser
def load(
resource_url,
format="auto",
cache=True,
verbose=F... | Load a grammar from a file, and build a parser based on that grammar. The parser depends on the grammar format, and might also depend on properties of the grammar itself. The following grammar formats are currently supported: - ``'cfg'`` (CFGs: ``CFG``) - ``'pcfg'`` (probabilistic CFGs: ``PCFG``) - ``'fcfg'`` (feature-... |
170,621 | from nltk.data import load
from nltk.grammar import CFG, PCFG, FeatureGrammar
from nltk.parse.chart import Chart, ChartParser
from nltk.parse.featurechart import FeatureChart, FeatureChartParser
from nltk.parse.pchart import InsideChartParser
def taggedsent_to_conll(sentence):
"""
A module to convert a single P... | A module to convert the a POS tagged document stream (i.e. list of list of tuples, a list of sentences) and yield lines in CONLL format. This module yields one line per word and two newlines for end of sentence. >>> from nltk import word_tokenize, sent_tokenize, pos_tag >>> text = "This is a foobar sentence. Is that ri... |
170,622 | from nltk.data import load
from nltk.grammar import CFG, PCFG, FeatureGrammar
from nltk.parse.chart import Chart, ChartParser
from nltk.parse.featurechart import FeatureChart, FeatureChartParser
from nltk.parse.pchart import InsideChartParser
The provided code snippet includes necessary dependencies for implementing t... | Parses a string with one test sentence per line. Lines can optionally begin with: - a bool, saying if the sentence is grammatical or not, or - an int, giving the number of parse trees is should have, The result information is followed by a colon, and then the sentence. Empty lines and lines beginning with a comment cha... |
170,623 | import logging
import math
from nltk.parse.dependencygraph import DependencyGraph
def nonprojective_conll_parse_demo():
from nltk.parse.dependencygraph import conll_data2
graphs = [DependencyGraph(entry) for entry in conll_data2.split("\n\n") if entry]
npp = ProbabilisticNonprojectiveParser()
npp.train(... | null |
170,624 | import logging
import math
from nltk.parse.dependencygraph import DependencyGraph
class DemoScorer(DependencyScorerI):
def train(self, graphs):
print("Training...")
def score(self, graph):
# scores for Keith Hall 'K-best Spanning Tree Parsing' paper
return [
[[], [5], [1], [1... | null |
170,625 | from nltk.grammar import Nonterminal
from nltk.parse.api import ParserI
from nltk.tree import ImmutableTree, Tree
class RecursiveDescentParser(ParserI):
"""
A simple top-down CFG parser that parses texts by recursively
expanding the fringe of a Tree, and matching it against a
text.
``RecursiveDescen... | A demonstration of the recursive descent parser. |
170,626 | 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,... | null |
170,627 | 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,... | null |
170,628 | from nltk.parse.api import ParserI
from nltk.tree import Tree
def _ensure_bllip_import_or_error():
pass | null |
170,629 | from nltk.parse.api import ParserI
from nltk.tree import Tree
def _ensure_bllip_import_or_error(ie=ie):
raise ImportError("Couldn't import bllipparser module: %s" % ie) | null |
170,630 | from nltk.parse.api import ParserI
from nltk.tree import Tree
def _ensure_ascii(words):
try:
for i, word in enumerate(words):
word.encode("ascii")
except UnicodeEncodeError as e:
raise ValueError(
f"Token {i} ({word!r}) is non-ASCII. BLLIP Parser "
"currently... | null |
170,631 | from nltk.parse.api import ParserI
from nltk.tree import Tree
def _scored_parse_to_nltk_tree(scored_parse):
return Tree.fromstring(str(scored_parse.ptb_parse)) | null |
170,632 | from nltk.parse.api import ParserI
from nltk.tree import Tree
class BllipParser(ParserI):
"""
Interface for parsing with BLLIP Parser. BllipParser objects can be
constructed with the ``BllipParser.from_unified_model_dir`` class
method or manually using the ``BllipParser`` constructor.
"""
def __... | This assumes the Python module bllipparser is installed. |
170,633 | import subprocess
import warnings
from collections import defaultdict
from itertools import chain
from pprint import pformat
from nltk.internals import find_binary
from nltk.tree import Tree
def find_binary(
name,
path_to_bin=None,
env_vars=(),
searchpath=(),
binary_names=None,
url=None,
ve... | Create image representation fom dot_string, using the 'dot' program from the Graphviz package. Use the 't' argument to specify the image file format, for ex. 'jpeg', 'eps', 'json', 'png' or 'webp' (Running 'dot -T:' lists all available formats). Note that the "capture_output" option of subprocess.run() is only availabl... |
170,634 | import subprocess
import warnings
from collections import defaultdict
from itertools import chain
from pprint import pformat
from nltk.internals import find_binary
from nltk.tree import Tree
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of t... | null |
170,635 | import random
from functools import reduce
from nltk.grammar import PCFG, Nonterminal
from nltk.parse.api import ParserI
from nltk.parse.chart import AbstractChartRule, Chart, LeafEdge, TreeEdge
from nltk.tree import ProbabilisticTree, Tree
class InsideChartParser(BottomUpProbabilisticChartParser):
"""
A bottom... | A demonstration of the probabilistic parsers. The user is prompted to select which demo to run, and how many parses should be found; and then each parser is run on the same demo, and a summary of the results are displayed. |
170,636 | import pickle
import tempfile
from copy import deepcopy
from operator import itemgetter
from os import remove
from nltk.parse import DependencyEvaluator, DependencyGraph, ParserI
The provided code snippet includes necessary dependencies for implementing the `demo` function. Write a Python function `def demo()` to solv... | >>> from nltk.parse import DependencyGraph, DependencyEvaluator >>> from nltk.parse.transitionparser import TransitionParser, Configuration, Transition >>> gold_sent = DependencyGraph(\""" ... Economic JJ 2 ATT ... news NN 3 SBJ ... has VBD 0 ROOT ... little JJ 5 ATT ... effect NN 3 OBJ ... on IN 5 ATT ... financial JJ... |
170,637 | from collections import defaultdict
from functools import total_ordering
from itertools import chain
from nltk.grammar import (
DependencyGrammar,
DependencyProduction,
ProbabilisticDependencyGrammar,
)
from nltk.internals import raise_unorderable_types
from nltk.parse.dependencygraph import DependencyGraph... | null |
170,638 | from collections import defaultdict
from functools import total_ordering
from itertools import chain
from nltk.grammar import (
DependencyGrammar,
DependencyProduction,
ProbabilisticDependencyGrammar,
)
from nltk.internals import raise_unorderable_types
from nltk.parse.dependencygraph import DependencyGraph... | A demonstration showing the creation of a ``DependencyGrammar`` in which a specific number of modifiers is listed for a given head. This can further constrain the number of possible parses created by a ``ProjectiveDependencyParser``. |
170,639 | 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
... | null |
170,640 | 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
... | A module to find MaltParser .jar file and its dependencies. |
170,641 | 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
... | A module to find pre-trained MaltParser model. |
170,642 | import json
import os
import re
import socket
import time
from typing import List, Tuple
from nltk.internals import _java_options, config_java, find_jar_iter, java
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
from nltk.tag.api import TaggerI
from nltk.tokenize.api import To... | null |
170,643 | import json
import os
import re
import socket
import time
from typing import List, Tuple
from nltk.internals import _java_options, config_java, find_jar_iter, java
from nltk.parse.api import ParserI
from nltk.parse.dependencygraph import DependencyGraph
from nltk.tag.api import TaggerI
from nltk.tokenize.api import To... | null |
170,644 | import itertools
import sys
from nltk.grammar import Nonterminal
def generate(grammar, start=None, depth=None, n=None):
demo_grammar = """
S -> NP VP
NP -> Det N
PP -> P NP
VP -> 'slept' | 'saw' NP | 'walked' PP
Det -> 'the' | 'a'
N -> 'man' | 'park' | 'dog'
P -> 'in' | 'with'
"""
class CFG:
def __i... | null |
170,645 | from nltk.grammar import Nonterminal
from nltk.parse.api import ParserI
from nltk.tree import Tree
class ShiftReduceParser(ParserI):
"""
A simple bottom-up CFG parser that uses two operations, "shift"
and "reduce", to find a single parse for a text.
``ShiftReduceParser`` maintains a stack, which records... | A demonstration of the shift-reduce parser. |
170,646 | import itertools
import re
import warnings
from functools import total_ordering
from nltk.grammar import PCFG, is_nonterminal, is_terminal
from nltk.internals import raise_unorderable_types
from nltk.parse.api import ParserI
from nltk.tree import Tree
from nltk.util import OrderedDict
def is_terminal(item):
"""
... | null |
170,647 | import itertools
import re
import warnings
from functools import total_ordering
from nltk.grammar import PCFG, is_nonterminal, is_terminal
from nltk.internals import raise_unorderable_types
from nltk.parse.api import ParserI
from nltk.tree import Tree
from nltk.util import OrderedDict
TD_STRATEGY = [
LeafInitRule()... | A demonstration of the chart parsers. |
170,648 | from time import perf_counter
from nltk.parse.chart import (
BottomUpPredictCombineRule,
BottomUpPredictRule,
CachedTopDownPredictRule,
Chart,
ChartParser,
EdgeI,
EmptyPredictRule,
FilteredBottomUpPredictCombineRule,
FilteredSingleEdgeFundamentalRule,
LeafEdge,
LeafInitRule,
... | A demonstration of the Earley parsers. |
170,649 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
class Nonterminal:
"""
... | :return: True if the item is a ``Nonterminal``. :rtype: bool |
170,650 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
def _read_production(line, non... | Return a list of context-free ``Productions``. |
170,651 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
def _read_production(line, non... | Return a list of PCFG ``ProbabilisticProductions``. |
170,652 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
def _read_production(line, non... | Return a list of feature-based ``Productions``. |
170,653 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
def _read_production(line, non... | Return a pair consisting of a starting category and a list of ``Productions``. :param input: a grammar, either in the form of a string or else as a list of strings. :param nonterm_parser: a function for parsing nonterminals. It should take a ``(string, position)`` as argument and return a ``(nonterminal, position)`` as... |
170,654 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
class DependencyProduction(Pro... | null |
170,655 | import re
from functools import total_ordering
from nltk.featstruct import SLASH, TYPE, FeatDict, FeatStruct, FeatStructReader
from nltk.internals import raise_unorderable_types
from nltk.probability import ImmutableProbabilisticMixIn
from nltk.util import invert_graph, transitive_closure
def cfg_demo():
"""
A ... | null |
170,656 | from nltk.tree.tree import Tree
def chomsky_normal_form(
tree, factor="right", horzMarkov=None, vertMarkov=0, childChar="|", parentChar="^"
):
# assume all subtrees have homogeneous children
# assume all terminals have no siblings
# A semi-hack to have elegant looking code below. As a result,
# any... | A demonstration showing how each tree transform can be used. |
170,657 | import re
from nltk.grammar import Nonterminal, Production
from nltk.internals import deprecated
class Tree(list):
r"""
A Tree represents a hierarchical grouping of leaves and subtrees.
For example, each constituent in a syntax tree is represented by a single Tree.
A tree's children are encoded as a lis... | null |
170,658 | import re
from nltk.grammar import Nonterminal, Production
from nltk.internals import deprecated
class Tree(list):
r"""
A Tree represents a hierarchical grouping of leaves and subtrees.
For example, each constituent in a syntax tree is represented by a single Tree.
A tree's children are encoded as a lis... | A demonstration showing how Trees and Trees can be used. This demonstration creates a Tree, and loads a Tree from the Treebank corpus, and shows the results of calling several of their methods. |
170,659 | import re
from nltk.tree.tree import Tree
The provided code snippet includes necessary dependencies for implementing the `bracket_parse` function. Write a Python function `def bracket_parse(s)` to solve the following problem:
Use Tree.read(s, remove_empty_top_bracketing=True) instead.
Here is the function:
def brack... | Use Tree.read(s, remove_empty_top_bracketing=True) instead. |
170,660 | import re
from nltk.tree.tree import Tree
class Tree(list):
r"""
A Tree represents a hierarchical grouping of leaves and subtrees.
For example, each constituent in a syntax tree is represented by a single Tree.
A tree's children are encoded as a list of leaves and subtrees,
where a leaf is a basic... | Parse a Sinica Treebank string and return a tree. Trees are represented as nested brackettings, as shown in the following example (X represents a Chinese character): S(goal:NP(Head:Nep:XX)|theme:NP(Head:Nhaa:X)|quantity:Dab:X|Head:VL2:X)#0(PERIODCATEGORY) :return: A tree corresponding to the string representation. :rty... |
170,661 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
_is_value = re.compile(r"\S")
The provided code snippet includes necessary dependencies for implementing the `to_sfm_string` function. Write a Python f... | Return a string with a standard format representation of the toolbox data in tree (tree can be a toolbox database or a single record). :param tree: flat representation of toolbox data (whole database or single record) :type tree: ElementTree._ElementInterface :param encoding: Name of an encoding to use. :type encoding:... |
170,662 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
The provided code snippet includes necessary dependencies for implementing the `remove_blanks` function. Write a Python function `def remove_blanks(ele... | Remove all elements and subelements with no text and no child elements. :param elem: toolbox data in an elementtree structure :type elem: ElementTree._ElementInterface |
170,663 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
def find(resource_name, paths=None):
"""
Find the given resource by searching through the directories and
zip files in paths, where a None ... | Add blank elements and subelements specified in default_fields. :param elem: toolbox data in an elementtree structure :type elem: ElementTree._ElementInterface :param default_fields: fields to add to each type of element and subelement :type default_fields: dict(tuple) |
170,664 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
def _sort_fields(elem, orders_dicts):
"""sort the children of elem"""
try:
order = orders_dicts[elem.tag]
except KeyError:
p... | Sort the elements and subelements in order specified in field_orders. :param elem: toolbox data in an elementtree structure :type elem: ElementTree._ElementInterface :param field_orders: order of fields for each type of element and subelement :type field_orders: dict(tuple) |
170,665 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
The provided code snippet includes necessary dependencies for implementing the `add_blank_lines` function. Write a Python function `def add_blank_lines... | Add blank lines before all elements and subelements specified in blank_before. :param elem: toolbox data in an elementtree structure :type elem: ElementTree._ElementInterface :param blank_before: elements and subelements to add blank lines before :type blank_before: dict(tuple) |
170,666 | import codecs
import re
from io import StringIO
from xml.etree.ElementTree import Element, ElementTree, SubElement, TreeBuilder
from nltk.data import PathPointer, find
class ToolboxData(StandardFormat):
def parse(self, grammar=None, **kwargs):
if grammar:
return self._chunk_parse(grammar=grammar... | null |
170,667 | import array
import math
import random
import warnings
from abc import ABCMeta, abstractmethod
from collections import Counter, defaultdict
from functools import reduce
from nltk.internals import raise_unorderable_types
_NINF = float("-1e300")
def add_logs(logx, logy):
def reduce(function: Callable[[_T, _S], _T], sequ... | null |
170,668 | import array
import math
import random
import warnings
from abc import ABCMeta, abstractmethod
from collections import Counter, defaultdict
from functools import reduce
from nltk.internals import raise_unorderable_types
def _get_kwarg(kwargs, key, default):
if key in kwargs:
arg = kwargs[key]
del k... | null |
170,669 | import array
import math
import random
import warnings
from abc import ABCMeta, abstractmethod
from collections import Counter, defaultdict
from functools import reduce
from nltk.internals import raise_unorderable_types
class FreqDist(Counter):
"""
A frequency distribution for the outcomes of an experiment. A
... | A demonstration of frequency distributions and probability distributions. This demonstration creates three frequency distributions with, and uses them to sample a random process with ``numsamples`` samples. Each frequency distribution is sampled ``numoutcomes`` times. These three frequency distributions are then used t... |
170,670 | import array
import math
import random
import warnings
from abc import ABCMeta, abstractmethod
from collections import Counter, defaultdict
from functools import reduce
from nltk.internals import raise_unorderable_types
class FreqDist(Counter):
def __init__(self, samples=None):
def N(self):
def __setitem... | null |
170,671 | import copy
import random
import sys
try:
import numpy
except ImportError:
pass
from nltk.cluster.util import VectorSpaceClusterer
class KMeansClusterer(VectorSpaceClusterer):
"""
The K-means clusterer starts with k arbitrary chosen means then allocates
each vector to the cluster with the closest me... | null |
170,672 | import copy
from abc import abstractmethod
from math import sqrt
from sys import stdout
try:
import numpy
except ImportError:
pass
from nltk.cluster.api import ClusterI
def sqrt(__x: SupportsFloat) -> float: ...
The provided code snippet includes necessary dependencies for implementing the `cosine_distance` f... | Returns 1 minus the cosine of the angle between vectors v and u. This is equal to ``1 - (u.v / |u||v|)``. |
170,673 | try:
import numpy
except ImportError:
pass
from nltk.cluster.util import Dendrogram, VectorSpaceClusterer, cosine_distance
class GAAClusterer(VectorSpaceClusterer):
"""
The Group Average Agglomerative starts with each of the N vectors as singleton
clusters. It then iteratively merges pairs of cluste... | Non-interactive demonstration of the clusterers with simple 2-D data. |
170,674 | try:
import numpy
except ImportError:
pass
from nltk.cluster.util import VectorSpaceClusterer
class EMClusterer(VectorSpaceClusterer):
"""
The Gaussian EM clusterer models the vectors as being produced by
a mixture of k Gaussian sources. The parameters of these sources
(prior probability, mean a... | Non-interactive demonstration of the clusterers with simple 2-D data. |
170,675 | import codecs
import functools
import os
import pickle
import re
import sys
import textwrap
import zipfile
from abc import ABCMeta, abstractmethod
from gzip import WRITE as GZ_WRITE
from gzip import GzipFile
from io import BytesIO, TextIOWrapper
from urllib.request import url2pathname, urlopen
from nltk import grammar,... | null |
170,676 | import codecs
import functools
import os
import pickle
import re
import sys
import textwrap
import zipfile
from abc import ABCMeta, abstractmethod
from gzip import WRITE as GZ_WRITE
from gzip import GzipFile
from io import BytesIO, TextIOWrapper
from urllib.request import url2pathname, urlopen
from nltk import grammar,... | Copy the given resource to a local file. If no filename is specified, then use the URL's filename. If there is already a file named ``filename``, then raise a ``ValueError``. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which se... |
170,677 | import codecs
import functools
import os
import pickle
import re
import sys
import textwrap
import zipfile
from abc import ABCMeta, abstractmethod
from gzip import WRITE as GZ_WRITE
from gzip import GzipFile
from io import BytesIO, TextIOWrapper
from urllib.request import url2pathname, urlopen
from nltk import grammar,... | Write out a grammar file, ignoring escaped and empty lines. :type resource_url: str :param resource_url: A URL specifying where the resource should be loaded from. The default protocol is "nltk:", which searches for the file in the the NLTK data package. :type escape: str :param escape: Prepended string that signals li... |
170,678 | import codecs
import functools
import os
import pickle
import re
import sys
import textwrap
import zipfile
from abc import ABCMeta, abstractmethod
from gzip import WRITE as GZ_WRITE
from gzip import GzipFile
from io import BytesIO, TextIOWrapper
from urllib.request import url2pathname, urlopen
from nltk import grammar,... | Remove all objects from the resource cache. :see: load() |
170,679 | 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
The provided code snippet includes necessary dependenc... | A timer decorator to measure execution performance of methods. |
170,680 | 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
def extract_unigram_feats(document, unigrams, handle_ne... | Train and test Naive Bayes classifier on 10000 tweets, tokenized using TweetTokenizer. Features are composed of: - 1000 most frequent unigrams - 100 top bigrams (using BigramAssocMeasures.pmi) :param trainer: `train` method of a classifier. :param n_instances: the number of total tweets that have to be used for trainin... |
170,681 | 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
def extract_unigram_feats(document, unigrams, handle_ne... | Train classifier on all instances of the Movie Reviews dataset. The corpus has been preprocessed using the default sentence tokenizer and WordPunctTokenizer. Features are composed of: - most frequent unigrams :param trainer: `train` method of a classifier. :param n_instances: the number of total reviews that have to be... |
170,682 | 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
def demo_subjectivity(trainer, save_analyzer=False, n_i... | Classify a single sentence as subjective or objective using a stored SentimentAnalyzer. :param text: a sentence whose subjectivity has to be classified. |
170,683 | 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
def _show_plot(x_values, y_values, x_labels=None, y_lab... | Basic example of sentiment classification using Liu and Hu opinion lexicon. This function simply counts the number of positive, negative and neutral words in the sentence and classifies it depending on which polarity is more represented. Words that do not appear in the lexicon are considered as neutral. :param sentence... |
170,684 | 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
The provided code snippet includes necessary dependenc... | Output polarity scores for a text using Vader approach. :param text: a text whose polarity has to be evaluated. |
170,685 | 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
def output_markdown(filename, **kwargs):
"""
Wr... | Classify 10000 positive and negative tweets using Vader approach. :param n_instances: the number of total tweets that have to be classified. :param output: the output file where results have to be reported. |
170,686 | import html
import re
from collections import defaultdict
def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
"""
Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern.
The parameters ``subjclass`` and ``objclass`` can be used to rest... | Select pairs of organizations and locations whose mentions occur with an intervening occurrence of the preposition "in". If the sql parameter is set to True, then the entity pairs are loaded into an in-memory database, and subsequently pulled out using an SQL "SELECT" query. |
170,687 | import html
import re
from collections import defaultdict
def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
"""
Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern.
The parameters ``subjclass`` and ``objclass`` can be used to rest... | null |
170,688 | import html
import re
from collections import defaultdict
ieer: IEERCorpusReader = LazyCorpusLoader("ieer", IEERCorpusReader, r"(?!README|\.).*")
def ieer_headlines():
from nltk.corpus import ieer
from nltk.tree import Tree
print("IEER: First 20 Headlines")
print("=" * 45)
trees = [
(do... | null |
170,689 | import html
import re
from collections import defaultdict
def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
"""
Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern.
The parameters ``subjclass`` and ``objclass`` can be used to rest... | Find the copula+'van' relation ('of') in the Dutch tagged training corpus from CoNLL 2002. |
170,690 | import html
import re
from collections import defaultdict
def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
def clause(reldict, relsym):
conll2002: ConllChunkCorpusReader = LazyCorpusLoader(
"conll2002",
ConllChunkCorpusReader,
r".*\.(test|train).*",
("LOC", "PER", "ORG... | null |
170,691 | import html
import re
from collections import defaultdict
def extract_rels(subjclass, objclass, doc, corpus="ace", pattern=None, window=10):
def rtuple(reldict, lcon=False, rcon=False):
def ne_chunked():
print()
print("1500 Sentences from Penn Treebank, as processed by NLTK NE Chunker")
print("=" * 45)
... | null |
170,692 | import codecs
from nltk.sem import evaluate
def interpret_sents(inputs, grammar, semkey="SEM", trace=0):
"""
Add the semantic representation to each syntactic parse tree
of each input sentence.
:param inputs: a list of sentences
:type inputs: list(str)
:param grammar: ``FeatureGrammar`` or name ... | Check that interpret_sents() is compatible with legacy grammars that use a lowercase 'sem' feature. Define 'test.fcfg' to be the following |
170,693 | import codecs
from nltk.sem import evaluate
def interpret_sents(inputs, grammar, semkey="SEM", trace=0):
"""
Add the semantic representation to each syntactic parse tree
of each input sentence.
:param inputs: a list of sentences
:type inputs: list(str)
:param grammar: ``FeatureGrammar`` or name ... | null |
170,694 | from nltk.parse import load_parser
from nltk.parse.featurechart import InstantiateVarsChart
from nltk.sem.logic import ApplicationExpression, LambdaExpression, Variable
class CooperStore:
"""
A container for handling quantifier ambiguity via Cooper storage.
"""
def __init__(self, featstruct):
""... | null |
170,695 | import os
from itertools import chain
import nltk
from nltk.internals import Counter
from nltk.sem import drt, linearlogic
from nltk.sem.logic import (
AbstractVariableExpression,
Expression,
LambdaExpression,
Variable,
VariableExpression,
)
from nltk.tag import BigramTagger, RegexpTagger, TrigramTa... | null |
170,696 | from nltk.internals import Counter
from nltk.sem.logic import APP, LogicParser
class Expression:
def fromstring(cls, s):
def applyto(self, other, other_indices=None):
def __call__(self, other):
def __repr__(self):
def demo():
lexpr = Expression.fromstring
print(lexpr(r"f"))
print(lexpr... | null |
170,697 | from nltk.parse import MaltParser
from nltk.sem.drt import DrsDrawer, DrtVariableExpression
from nltk.sem.glue import DrtGlue
from nltk.sem.logic import Variable
from nltk.tag import RegexpTagger
from nltk.util import in_idle
class DrtGlueDemo:
def __init__(self, examples):
# Set up the main window.
... | null |
170,698 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class Tokens:
LAMBDA = "\\"
LAMBDA_LIST = ["\\"]
# Quantifiers
EXISTS = "exists"
EXISTS_LIST = ["some", "exists", "exist"]
ALL ... | Boolean operators |
170,699 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class Tokens:
LAMBDA = "\\"
LAMBDA_LIST = ["\\"]
# Quantifiers
EXISTS = "exists"
EXISTS_LIST = ["some", "exists", "exist"]
ALL ... | Equality predicates |
170,700 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class Tokens:
LAMBDA = "\\"
LAMBDA_LIST = ["\\"]
# Quantifiers
EXISTS = "exists"
EXISTS_LIST = ["some", "exists", "exist"]
ALL ... | Binding operators |
170,701 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class LogicParser:
"""A lambda calculus expression parser."""
def __init__(self, type_check=False):
"""
:param type_check: shou... | Convert a file of First Order Formulas into a list of {Expression}s. :param s: the contents of the file :type s: str :param logic_parser: The parser to be used to parse the logical expression :type logic_parser: LogicParser :param encoding: the encoding of the input string, if it is binary :type encoding: str :return: ... |
170,702 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class ComplexType(Type):
def __init__(self, first, second):
assert isinstance(first, Type), "%s is not a Type" % first
assert isins... | null |
170,703 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
The provided code snippet includes necessary dependencies for implementing the `typecheck` function. Write a Python function `def typecheck(expression... | Ensure correct typing across a collection of ``Expression`` objects. :param expressions: a collection of expressions :param signature: dict that maps variable names to types (or string representations of types) |
170,704 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
class Variable:
def __init__(self, name):
"""
:param name: the name of the variable
"""
assert isinstance(name, str... | null |
170,705 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
def demoException(s):
try:
Expression.fromstring(s)
except LogicalExpressionException as e:
print(f"{e.__class__.__name__}: {e}... | null |
170,706 | import operator
import re
from collections import defaultdict
from functools import reduce, total_ordering
from nltk.internals import Counter
from nltk.util import Trie
def printtype(ex):
print(f"{ex.str()} : {ex.type}") | null |
170,707 | 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 skolem... | null |
170,708 | import os
import re
import shelve
import sys
import nltk.data
def _str2records(filename, rel):
"""
Read a file into memory and convert each relation clause into a list.
"""
recs = []
contents = nltk.data.load("corpora/chat80/%s" % filename, format="text")
for line in contents.splitlines():
... | Convert a file of Prolog clauses into a database table. This is not generic, since it doesn't allow arbitrary schemas to be set as a parameter. Intended usage:: cities2table('cities.pl', 'city', 'city.db', verbose=True, setup=True) :param filename: filename containing the relations :type filename: str :param rel_name: ... |
170,709 | import os
import re
import shelve
import sys
import nltk.data
def process_bundle(rels):
"""
Given a list of relation metadata bundles, make a corresponding
dictionary of concepts, indexed by the relation name.
:param rels: bundle of metadata needed for constructing a concept
:type rels: list(dict)
... | Make a ``Valuation`` from a list of relation metadata bundles and dump to persistent database. :param rels: bundle of metadata needed for constructing a concept :type rels: list of dict :param db: name of file to which data is written. The suffix '.db' will be automatically appended. :type db: str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.