id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
170,810
from abc import ABCMeta, abstractmethod from nltk.ccg.api import FunctionalCategory def innermostFunction(categ): while categ.res().is_function(): categ = categ.res() return categ def forwardTConstraint(left, right): arg = innermostFunction(right) return arg.dir().is_backward() and arg.res().is...
null
170,811
from abc import ABCMeta, abstractmethod from nltk.ccg.api import FunctionalCategory def innermostFunction(categ): while categ.res().is_function(): categ = categ.res() return categ def backwardTConstraint(left, right): arg = innermostFunction(left) return arg.dir().is_forward() and arg.res().is_...
null
170,812
from nltk.sem.logic import * def compute_type_raised_semantics(semantics): core = semantics parent = None while isinstance(core, LambdaExpression): parent = core core = core.term var = Variable("F") while var in core.free(): var = unique_variable(pattern=var) core = App...
null
170,813
from nltk.sem.logic import * def compute_function_semantics(function, argument): return ApplicationExpression(function, argument).simplify()
null
170,814
from nltk.sem.logic import * def compute_composition_semantics(function, argument): assert isinstance(argument, LambdaExpression), ( "`" + str(argument) + "` must be a lambda expression" ) return LambdaExpression( argument.variable, ApplicationExpression(function, argument.term).simplify() ...
null
170,815
from nltk.sem.logic import * def compute_substitution_semantics(function, argument): assert isinstance(function, LambdaExpression) and isinstance( function.term, LambdaExpression ), ("`" + str(function) + "` must be a lambda expression with 2 arguments") assert isinstance(argument, LambdaExpression...
null
170,816
import itertools from nltk.ccg.combinator import * from nltk.ccg.combinator import ( BackwardApplication, BackwardBx, BackwardComposition, BackwardSx, BackwardT, ForwardApplication, ForwardComposition, ForwardSubstitution, ForwardT, ) from nltk.ccg.lexicon import Token, fromstring fr...
null
170,817
import itertools from nltk.ccg.combinator import * from nltk.ccg.combinator import ( BackwardApplication, BackwardBx, BackwardComposition, BackwardSx, BackwardT, ForwardApplication, ForwardComposition, ForwardSubstitution, ForwardT, ) from nltk.ccg.lexicon import Token, fromstring fr...
null
170,818
import json json_tags = {} TAG_PREFIX = "!" The provided code snippet includes necessary dependencies for implementing the `register_tag` function. Write a Python function `def register_tag(cls)` to solve the following problem: Decorates a class to register it's json tag. Here is the function: def register_tag(cls):...
Decorates a class to register it's json tag.
170,819
import re from textwrap import wrap from nltk.data import load def _format_tagset(tagset, tagpattern=None): tagdict = load("help/tagsets/" + tagset + ".pickle") if not tagpattern: _print_entries(sorted(tagdict), tagdict) elif tagpattern in tagdict: _print_entries([tagpattern], tagdict) e...
null
170,820
import re from textwrap import wrap from nltk.data import load def _format_tagset(tagset, tagpattern=None): tagdict = load("help/tagsets/" + tagset + ".pickle") if not tagpattern: _print_entries(sorted(tagdict), tagdict) elif tagpattern in tagdict: _print_entries([tagpattern], tagdict) e...
null
170,821
import re from textwrap import wrap from nltk.data import load def _format_tagset(tagset, tagpattern=None): tagdict = load("help/tagsets/" + tagset + ".pickle") if not tagpattern: _print_entries(sorted(tagdict), tagdict) elif tagpattern in tagdict: _print_entries([tagpattern], tagdict) e...
null
170,822
The provided code snippet includes necessary dependencies for implementing the `tuple2str` function. Write a Python function `def tuple2str(tagged_token, sep="/")` to solve the following problem: Given the tuple representation of a tagged token, return the corresponding string representation. This representation is f...
Given the tuple representation of a tagged token, return the corresponding string representation. This representation is formed by concatenating the token's word string, followed by the separator, followed by the token's tag. (If the tag is None, then just return the bare word string.) >>> from nltk.tag.util import tup...
170,823
The provided code snippet includes necessary dependencies for implementing the `untag` function. Write a Python function `def untag(tagged_sentence)` to solve the following problem: Given a tagged sentence, return an untagged version of that sentence. I.e., return a list containing the first element of each tuple in ...
Given a tagged sentence, return an untagged version of that sentence. I.e., return a list containing the first element of each tuple in *tagged_sentence*. >>> from nltk.tag.util import untag >>> untag([('John', 'NNP'), ('saw', 'VBD'), ('Mary', 'NNP')]) ['John', 'saw', 'Mary']
170,824
from collections import Counter, defaultdict from nltk import jsontags from nltk.tag import TaggerI from nltk.tbl import Feature, Template class Word(Feature): """ Feature which examines the text (word) of nearby tokens. """ json_tag = "nltk.tag.brill.Word" def extract_property(tokens, index): ...
Return 18 templates, from the original nltk demo, and additionally a few multi-feature ones (the motivation is easy comparison with nltkdemo18)
170,825
from collections import Counter, defaultdict from nltk import jsontags from nltk.tag import TaggerI from nltk.tbl import Feature, Template class Word(Feature): """ Feature which examines the text (word) of nearby tokens. """ json_tag = "nltk.tag.brill.Word" def extract_property(tokens, index): ...
Return 37 templates taken from the postagging task of the fntbl distribution https://www.cs.jhu.edu/~rflorian/fntbl/ (37 is after excluding a handful which do not condition on Pos[0]; fntbl can do that but the current nltk implementation cannot.)
170,826
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,827
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,828
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,829
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
Adds the logged values, returning the logarithm of the addition.
170,830
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,831
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,832
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,833
import itertools import re from nltk.metrics import accuracy from nltk.probability import ( ConditionalFreqDist, ConditionalProbDist, DictionaryConditionalProbDist, DictionaryProbDist, FreqDist, LidstoneProbDist, MLEProbDist, MutableProbDist, RandomProbDist, ) from nltk.tag.api impor...
null
170,834
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 def _pc(n, d): return (n / d) * 100
null
170,835
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 PICKLE = "averaged_perceptron_tagger.pickle" class PerceptronTagger(TaggerI): """ Greedy Averaged Perceptron tagger, as implemented by Matthe...
null
170,836
from math import log from operator import itemgetter from nltk.probability import ConditionalFreqDist, FreqDist from nltk.tag.api import TaggerI The provided code snippet includes necessary dependencies for implementing the `basic_sent_chop` function. Write a Python function `def basic_sent_chop(data, raw=True)` to so...
Basic method for tokenizing input into sentences for this tagger: :param data: list of tokens (words or (word, tag) tuples) :type data: str or tuple(str, str) :param raw: boolean flag marking the input data as a list of words or a list of tagged words :type raw: bool :return: list of sentences sentences are a list of t...
170,837
from math import log from operator import itemgetter from nltk.probability import ConditionalFreqDist, FreqDist from nltk.tag.api import TaggerI class TnT(TaggerI): """ TnT - Statistical POS tagger IMPORTANT NOTES: * DOES NOT AUTOMATICALLY DEAL WITH UNSEEN WORDS - It is possible to provide an untr...
null
170,838
from math import log from operator import itemgetter from nltk.probability import ConditionalFreqDist, FreqDist from nltk.tag.api import TaggerI class TnT(TaggerI): """ TnT - Statistical POS tagger IMPORTANT NOTES: * DOES NOT AUTOMATICALLY DEAL WITH UNSEEN WORDS - It is possible to provide an untr...
null
170,839
from math import log from operator import itemgetter from nltk.probability import ConditionalFreqDist, FreqDist from nltk.tag.api import TaggerI class TnT(TaggerI): """ TnT - Statistical POS tagger IMPORTANT NOTES: * DOES NOT AUTOMATICALLY DEAL WITH UNSEEN WORDS - It is possible to provide an untr...
null
170,840
from nltk.chat.util import Chat, reflections def eliza_chat(): print("Therapist\n---------") print("Talk to the program by typing in plain English, using normal upper-") print('and lower-case letters and punctuation. Enter "quit" when done.') print("=" * 72) print("Hello. How are you feeling today...
null
170,841
from nltk.chat.util import Chat, reflections def zen_chat(): print("*" * 75) print("Zen Chatbot!".center(75)) print("*" * 75) print('"Look beyond mere words and letters - look into your mind"'.center(75)) print("* Talk your way to truth with Zen Chatbot.") print("* Type 'quit' when you have had ...
null
170,842
from nltk.chat.util import Chat, reflections def rude_chat(): print("Talk to the program by typing in plain English, using normal upper-") print('and lower-case letters and punctuation. Enter "quit" when done.') print("=" * 72) print("I suppose I should say hello.") rude_chatbot.converse() def dem...
null
170,843
from nltk.chat.util import Chat, reflections def suntsu_chat(): print("Talk to the program by typing in plain English, using normal upper-") print('and lower-case letters and punctuation. Enter "quit" when done.') print("=" * 72) print("You seek enlightenment?") suntsu_chatbot.converse() def demo(...
null
170,844
from nltk.chat.util import Chat def iesha_chat(): print("Iesha the TeenBoT\n---------") print("Talk to the program by typing in plain English, using normal upper-") print('and lower-case letters and punctuation. Enter "quit" when done.') print("=" * 72) print("hi!! i'm iesha! who r u??!") iesha...
null
170,845
import os from functools import wraps def add_py3_data(path): def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: def py3_data(init_func): def _decorator(*args, **kwargs): args = (args[0], add_py3_data(args[1])) + args[2:] return ini...
null
170,846
import math import nltk.classify.util from nltk.util import LazyMap The provided code snippet includes necessary dependencies for implementing the `apply_features` function. Write a Python function `def apply_features(feature_func, toks, labeled=None)` to solve the following problem: Use the ``LazyMap`` class to cons...
Use the ``LazyMap`` class to construct a lazy list-like object that is analogous to ``map(feature_func, toks)``. In particular, if ``labeled=False``, then the returned list-like object's values are equal to:: [feature_func(tok) for tok in toks] If ``labeled=True``, then the returned list-like object's values are equal ...
170,847
import math import nltk.classify.util from nltk.util import LazyMap The provided code snippet includes necessary dependencies for implementing the `attested_labels` function. Write a Python function `def attested_labels(tokens)` to solve the following problem: :return: A list of all labels that are attested in the gi...
:return: A list of all labels that are attested in the given list of tokens. :rtype: list of (immutable) :param tokens: The list of classified tokens from which to extract labels. A classified token has the form ``(token, label)``. :type tokens: list
170,848
import math import nltk.classify.util from nltk.util import LazyMap def accuracy(classifier, gold): results = classifier.classify_many([fs for (fs, l) in gold]) correct = [l == r for ((fs, l), r) in zip(gold, results)] if correct: return sum(correct) / len(correct) else: return 0 _inst_...
null
170,849
import math import nltk.classify.util from nltk.util import LazyMap The provided code snippet includes necessary dependencies for implementing the `check_megam_config` function. Write a Python function `def check_megam_config()` to solve the following problem: Checks whether the MEGAM binary is configured. Here is t...
Checks whether the MEGAM binary is configured.
170,850
from nltk.classify.maxent import MaxentClassifier from nltk.classify.util import accuracy from nltk.tokenize import RegexpTokenizer def rte_featurize(rte_pairs): return [(rte_features(pair), pair.value) for pair in rte_pairs] class MaxentClassifier(ClassifierI): """ A maximum entropy classifier (also known...
null
170,851
from sys import maxsize from nltk.util import trigrams class TextCat: _corpus = None fingerprints = {} _START_CHAR = "<" _END_CHAR = ">" last_distances = {} def __init__(self): if not re: raise OSError( "classify.textcat requires the regex module that " ...
null
170,852
from collections import defaultdict from nltk.classify.naivebayes import NaiveBayesClassifier from nltk.probability import DictionaryProbDist, ELEProbDist, FreqDist class PositiveNaiveBayesClassifier(NaiveBayesClassifier): def train( positive_featuresets, unlabeled_featuresets, positive_prob...
null
170,853
try: import numpy except ImportError: pass import os import tempfile from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.classify.megam import call_megam, parse_megam_weights, write_megam_file from nltk.classify.tadm import call_tadm, parse_tadm_weights, write_tadm_file from ...
Train a new ``ConditionalExponentialClassifier``, using the given training samples, using the Generalized Iterative Scaling algorithm. This ``ConditionalExponentialClassifier`` will encode the model that maximizes entropy from all the models that are empirically consistent with ``train_toks``. :see: ``train_maxent_clas...
170,854
try: import numpy except ImportError: pass import os import tempfile from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.classify.megam import call_megam, parse_megam_weights, write_megam_file from nltk.classify.tadm import call_tadm, parse_tadm_weights, write_tadm_file from ...
Train a new ``ConditionalExponentialClassifier``, using the given training samples, using the Improved Iterative Scaling algorithm. This ``ConditionalExponentialClassifier`` will encode the model that maximizes entropy from all the models that are empirically consistent with ``train_toks``. :see: ``train_maxent_classif...
170,855
try: import numpy except ImportError: pass import os import tempfile from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.classify.megam import call_megam, parse_megam_weights, write_megam_file from nltk.classify.tadm import call_tadm, parse_tadm_weights, write_tadm_file from ...
Train a new ``ConditionalExponentialClassifier``, using the given training samples, using the external ``megam`` library. This ``ConditionalExponentialClassifier`` will encode the model that maximizes entropy from all the models that are empirically consistent with ``train_toks``. :see: ``train_maxent_classifier()`` fo...
170,856
import os import tempfile from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.classify.megam import call_megam, parse_megam_weights, write_megam_file from nltk.classify.tadm import call_tadm, parse_tadm_weights, write_tadm_file from nltk.classify.util import CutoffChecker, accuracy, ...
null
170,857
import subprocess import sys from nltk.internals import find_binary try: import numpy except ImportError: pass The provided code snippet includes necessary dependencies for implementing the `parse_tadm_weights` function. Write a Python function `def parse_tadm_weights(paramfile)` to solve the following problem...
Given the stdout output generated by ``tadm`` when training a model, return a ``numpy`` array containing the corresponding weight vector.
170,858
import subprocess import sys from nltk.internals import find_binary _tadm_bin = None def config_tadm(bin=None): global _tadm_bin _tadm_bin = find_binary( "tadm", bin, env_vars=["TADM"], binary_names=["tadm"], url="http://tadm.sf.net" ) The provided code snippet includes necessary dependencies for i...
Call the ``tadm`` binary with the given arguments.
170,859
import subprocess import sys from nltk.internals import find_binary def write_tadm_file(train_toks, encoding, stream): """ Generate an input file for ``tadm`` based on the given corpus of classified tokens. :type train_toks: list(tuple(dict, str)) :param train_toks: Training data, represented as a l...
null
170,860
from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.probability import FreqDist, MLEProbDist, entropy def f(x): return DecisionTreeClassifier.train(x, binary=True, verbose=True) def binary_names_demo_features(name): features = {} features["alwayson"] = True features[...
null
170,861
from collections import defaultdict from nltk.classify.api import ClassifierI from nltk.probability import DictionaryProbDist, ELEProbDist, FreqDist, sum_logs class NaiveBayesClassifier(ClassifierI): def __init__(self, label_probdist, feature_probdist): def labels(self): def classify(self, featureset): ...
null
170,862
import os import re import subprocess import tempfile import time import zipfile from sys import stdin from nltk.classify.api import ClassifierI from nltk.internals import config_java, java from nltk.probability import DictionaryProbDist _weka_classpath = None _weka_search = [ ".", "/usr/share/weka", "/usr/...
null
170,863
import os import re import subprocess import tempfile import time import zipfile from sys import stdin from nltk.classify.api import ClassifierI from nltk.internals import config_java, java from nltk.probability import DictionaryProbDist class WekaClassifier(ClassifierI): def __init__(self, formatter, model_filenam...
null
170,864
from matplotlib import pylab from nltk.corpus import gutenberg from nltk.text import Text def plot_word_freq_dist(text): fd = text.vocab() samples = [item for item, _ in fd.most_common(50)] values = [fd[sample] for sample in samples] values = [sum(values[: i + 1]) * 100.0 / fd.N() for i in range(len(val...
null
170,865
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Extract the unique counter from the URL if it has one. Otherwise return null.
170,866
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
null
170,867
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
null
170,868
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Return a HTML page of NLTK Browser format constructed from the word and body :param word: The word that the body corresponds to :type word: str :param body: The HTML body corresponding to the word :type body: str :return: a HTML page for the word-body combination :rtype: str
170,869
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
null
170,870
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
abbc = asterisks, breaks, bold, center
170,871
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
The synset key is the unique name of the synset, this can be retrieved via synset.name()
170,872
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Return a HTML page for the given word. :type word: str :param word: The currently active word :return: A tuple (page,word), where page is the new current HTML page to be sent to the browser and word is the new current word :rtype: A tuple (str,str)
170,873
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Returns a tuple of the HTML page built and the new current word :param href: The hypertext reference to be solved :type href: str :return: A tuple (page,word), where page is the new current HTML page to be sent to the browser and word is the new current word :rtype: A tuple (str,str)
170,874
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Return a static HTML page from the path given.
170,875
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
Get the static welcome page.
170,876
import base64 import copy import getopt import io import os import pickle import sys import threading import time import webbrowser from collections import defaultdict from http.server import BaseHTTPRequestHandler, HTTPServer from sys import argv from urllib.parse import unquote_plus from nltk.corpus import wordnet as...
null
170,877
import itertools import re from tkinter import SEL_FIRST, SEL_LAST, Frame, Label, PhotoImage, Scrollbar, Text, Tk windowTitle = "Finding (and Replacing) Nemo" initialFind = r"n(.*?)e(.*?)m(.*?)o" initialRepl = r"M\1A\2K\3I" initialText = """\ Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod temp...
null
170,878
import random import re import textwrap import time from tkinter import ( Button, Canvas, Checkbutton, Frame, IntVar, Label, Menu, Scrollbar, Text, Tk, ) from tkinter.filedialog import askopenfilename, asksaveasfilename from tkinter.font import Font from nltk.chunk import ChunkSc...
null
170,879
from tkinter import Button, Frame, IntVar, Label, Listbox, Menu, Scrollbar, Tk from tkinter.font import Font from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment from nltk.draw.util import CanvasFrame, EntryDialog, ShowText, TextWidget from nltk.parse import SteppingRecursiveDescentParser from nltk.t...
Create a recursive descent parser demo, using a simple grammar and text.
170,880
import queue as q import threading from tkinter import ( END, LEFT, SUNKEN, Button, Frame, IntVar, Label, Menu, OptionMenu, Scrollbar, StringVar, Text, Tk, ) from tkinter.font import Font from nltk.corpus import ( alpino, brown, cess_cat, cess_esp, ...
null
170,881
import queue as q import re import threading from tkinter import ( END, LEFT, SUNKEN, Button, Entry, Frame, IntVar, Label, Menu, OptionMenu, Scrollbar, StringVar, Text, Tk, ) from tkinter.font import Font from nltk.corpus import ( alpino, brown, cess_c...
null
170,882
from tkinter import Button, Frame, IntVar, Label, Listbox, Menu, Scrollbar, Tk from tkinter.font import Font from nltk.draw import CFGEditor, TreeSegmentWidget, tree_to_treesegment from nltk.draw.util import CanvasFrame, EntryDialog, ShowText, TextWidget from nltk.parse import SteppingShiftReduceParser from nltk.tree i...
Create a shift reduce parser app, using a simple grammar and text.
170,883
import os.path import pickle from tkinter import ( Button, Canvas, Checkbutton, Frame, IntVar, Label, Menu, Scrollbar, Tk, Toplevel, ) from tkinter.filedialog import askopenfilename, asksaveasfilename from tkinter.font import Font from tkinter.messagebox import showerror, showinf...
null
170,884
import re from warnings import warn from nltk.corpus import bcp47 def langname(tag, typ="full"): """ Convert a composite BCP-47 tag to a language name >>> from nltk.langnames import langname >>> langname('ca-Latn-ES-valencia') 'Catalan: Latin: Spain: Valencian' >>> langname('ca-Latn-ES-valencia'...
Convert Wikidata Q-code to BCP-47 (full or short) language name >>> q2name('Q4289225') 'Low German: Mecklenburg-Vorpommern' >>> q2name('Q4289225', "short") 'Low German'
170,885
import re from warnings import warn from nltk.corpus import bcp47 def langcode(name, typ=2): """ Convert language name to iso639-3 language code. Returns the short 2-letter code by default, if one is available, and the 3-letter code otherwise: >>> from nltk.langnames import langcode >>> langcode('Mo...
Convert simple language name to Wikidata Q-code >>> lang2q('Low German') 'Q25433'
170,886
import re from warnings import warn from nltk.corpus import bcp47 The provided code snippet includes necessary dependencies for implementing the `inverse_dict` function. Write a Python function `def inverse_dict(dic)` to solve the following problem: Return inverse mapping, but only if it is bijective Here is the func...
Return inverse mapping, but only if it is bijective
170,887
The provided code snippet includes necessary dependencies for implementing the `suffix_replace` function. Write a Python function `def suffix_replace(original, old, new)` to solve the following problem: Replaces the old suffix of the original string by a new suffix Here is the function: def suffix_replace(original,...
Replaces the old suffix of the original string by a new suffix
170,888
The provided code snippet includes necessary dependencies for implementing the `prefix_replace` function. Write a Python function `def prefix_replace(original, old, new)` to solve the following problem: Replaces the old prefix of the original string by a new suffix :param original: string :param old: string :param ne...
Replaces the old prefix of the original string by a new suffix :param original: string :param old: string :param new: string :return: string
170,889
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): """ Snowball Stemmer The following languages are supported: Arabic, Danish, Dutch, English, Finnish, Fren...
This function provides a demonstration of the Snowball stemmers. After invoking this function and specifying a language, it stems an excerpt of the Universal Declaration of Human Rights (which is a part of the NLTK corpus collection) and then prints out the original and the stemmed text.
170,890
import re from nltk.stem.api import StemmerI class PorterStemmer(StemmerI): """ A word stemmer based on the Porter stemming algorithm. Porter, M. "An algorithm for suffix stripping." Program 14.3 (1980): 130-137. See https://www.tartarus.org/~martin/PorterStemmer/ for the homepage of the...
A demonstration of the porter stemmer on a sample from the Penn Treebank corpus.
170,891
def selection(a): """ Selection Sort: scan the list to find its smallest element, then swap it with the first element. The remainder of the list is one element smaller; apply the same method to this list, and so on. """ count = 0 for i in range(len(a) - 1): min = i for j in ...
null
170,892
import random def wordfinder(words, rows=20, cols=20, attempts=50, alph="ABCDEFGHIJKLMNOPQRSTUVWXYZ"): """ Attempt to arrange words into a letter-grid with the specified number of rows and columns. Try each word in several positions and directions, until it can be fitted into the grid, or the maxim...
null
170,893
def babelize_shell(): print("Babelfish online translation service is no longer available.")
null
170,894
leadins = """To characterize a linguistic level L, On the other hand, This suggests that It appears that Furthermore, We will bring evidence in favor of the following thesis: To provide a constituent structure for T(Z,K), From C1, it follows that For any transformation which is sufficien...
null
170,895
import re from nltk.metrics import accuracy as _accuracy from nltk.tag.mapping import map_tag from nltk.tag.util import str2tuple from nltk.tree import Tree def tree2conlltags(t): """ Return a list of 3-tuples containing ``(word, tag, IOB-tag)``. Convert a tree to the CoNLL IOB tag format. :param t: The...
Score the accuracy of the chunker against the gold standard. Strip the chunk information from the gold standard and rechunk it using the chunker, then compute the accuracy score. :type chunker: ChunkParserI :param chunker: The chunker being evaluated. :type gold: tree :param gold: The chunk structures to score the chun...
170,896
import re from nltk.metrics import accuracy as _accuracy from nltk.tag.mapping import map_tag from nltk.tag.util import str2tuple from nltk.tree import Tree def _chunksets(t, count, chunk_label): pos = 0 chunks = [] for child in t: if isinstance(child, Tree): if re.match(chunk_label, ch...
null
170,897
import re from nltk.metrics import accuracy as _accuracy from nltk.tag.mapping import map_tag from nltk.tag.util import str2tuple from nltk.tree import Tree The provided code snippet includes necessary dependencies for implementing the `conlltags2tree` function. Write a Python function `def conlltags2tree( sentenc...
Convert the CoNLL IOB format to a tree.
170,898
import re from nltk.metrics import accuracy as _accuracy from nltk.tag.mapping import map_tag from nltk.tag.util import str2tuple from nltk.tree import Tree _IEER_DOC_RE = re.compile( r"<DOC>\s*" r"(<DOCNO>\s*(?P<docno>.+?)\s*</DOCNO>\s*)?" r"(<DOCTYPE>\s*(?P<doctype>.+?)\s*</DOCTYPE>\s*)?" r"(<DATE_TIM...
Return a chunk structure containing the chunked tagged text that is encoded in the given IEER style string. Convert a string of chunked tagged text in the IEER named entity format into a chunk structure. Chunks are of several types, LOCATION, ORGANIZATION, PERSON, DURATION, DATE, CARDINAL, PERCENT, MONEY, and MEASURE. ...
170,899
import re from nltk.metrics import accuracy as _accuracy from nltk.tag.mapping import map_tag from nltk.tag.util import str2tuple from nltk.tree import Tree def tagstr2tree( s, chunk_label="NP", root_label="S", sep="/", source_tagset=None, target_tagset=None ): """ Divide a string of bracketted tagged text ...
null
170,900
import os import pickle import re from xml.etree import ElementTree as ET from nltk.tag import ClassifierBasedTagger, pos_tag from nltk.chunk.api import ChunkParserI from nltk.chunk.util import ChunkScore from nltk.data import find from nltk.tokenize import word_tokenize from nltk.tree import Tree def shape(word): ...
null
170,901
import os import pickle import re from xml.etree import ElementTree as ET from nltk.tag import ClassifierBasedTagger, pos_tag from nltk.chunk.api import ChunkParserI from nltk.chunk.util import ChunkScore from nltk.data import find from nltk.tokenize import word_tokenize from nltk.tree import Tree def simplify_pos(s):...
null
170,902
import os import pickle import re from xml.etree import ElementTree as ET from nltk.tag import ClassifierBasedTagger, pos_tag from nltk.chunk.api import ChunkParserI from nltk.chunk.util import ChunkScore from nltk.data import find from nltk.tokenize import word_tokenize from nltk.tree import Tree class NEChunkParser(C...
null
170,903
import re import regex from nltk.chunk.api import ChunkParserI from nltk.tree import Tree class ChunkString: """ A string-based encoding of a particular chunking of a text. Internally, the ``ChunkString`` class uses a single string to encode the chunking of the input text. This string contains a se...
Convert a tag pattern to a regular expression pattern. A "tag pattern" is a modified version of a regular expression, designed for matching sequences of tags. The differences between regular expression patterns and tag patterns are: - In tag patterns, ``'<'`` and ``'>'`` act as parentheses; so ``'<NN>+'`` matches one o...
170,904
import re import regex from nltk.chunk.api import ChunkParserI from nltk.tree import Tree class RegexpParser(ChunkParserI): r""" A grammar based chunk parser. ``chunk.RegexpParser`` uses a set of regular expression patterns to specify the behavior of the parser. The chunking of the text is encoded usin...
A demonstration for the ``RegexpChunkParser`` class. A single text is parsed with four different chunk parsers, using a variety of rules and strategies.
170,905
import itertools as _itertools from nltk.metrics import ( BigramAssocMeasures, ContingencyMeasures, QuadgramAssocMeasures, TrigramAssocMeasures, ) from nltk.metrics.spearman import ranks_from_scores, spearman_correlation from nltk.probability import FreqDist from nltk.util import ngrams class BigramColl...
Finds bigram collocations in the files of the WebText corpus.
170,906
import html from typing import List import regex from nltk.tokenize.api import TokenizerI ENT_RE = regex.compile(r"&(#?(x?))([^&;\s]+);") def _str_to_unicode(text, encoding=None, errors="strict"): if encoding is None: encoding = "utf-8" if isinstance(text, bytes): return text.decode(encoding, e...
Remove entities from text by converting them to their corresponding unicode character. :param text: a unicode string or a byte string encoded in the given `encoding` (which defaults to 'utf-8'). :param list keep: list of entity names which should not be replaced.\ This supports both numeric entities (``&#nnnn;`` and ``...
170,907
import html from typing import List import regex from nltk.tokenize.api import TokenizerI The provided code snippet includes necessary dependencies for implementing the `reduce_lengthening` function. Write a Python function `def reduce_lengthening(text)` to solve the following problem: Replace repeated character sequ...
Replace repeated character sequences of length 3 or greater with sequences of length 3.
170,908
import html from typing import List import regex from nltk.tokenize.api import TokenizerI HANDLES_RE = regex.compile( r"(?<![A-Za-z0-9_!@#\$%&*])@" r"(([A-Za-z0-9_]){15}(?!@)|([A-Za-z0-9_]){1,14}(?![A-Za-z0-9_]*@))" ) The provided code snippet includes necessary dependencies for implementing the `remove_handl...
Remove Twitter username handles from text.
170,909
import html from typing import List import regex from nltk.tokenize.api import TokenizerI class TweetTokenizer(TokenizerI): r""" Tokenizer for tweets. >>> from nltk.tokenize import TweetTokenizer >>> tknzr = TweetTokenizer() >>> s0 = "This is a cooool #dummysmiley: :-) :-P <3 and some a...
Convenience function for wrapping the tokenizer.