output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def add_gtc_header_table_row(t, telpars): """ Add a row with current values to GTC table Arguments --------- t : `~astropy.table.Table` The table to append row to telpars : list list returned by server call to getTelescopeParams """ now = Time.now().mjd hdr = create_...
Write a Python 3 function for adding a row with current values to GTC table with current values
As a python code expert, you are capable of creating scripts from specifications.
Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.plugin_info_pb2.PluginInfoProto :return: the PluginInfo :rtype: ~unidown.plugin.plugin_info.PluginInfo :raises ValueError: name of PluginInfo does not exist or is empty inside the p...
Can you generate a brief explanation for the following Python 3 code def from_protobuf(cls, proto: PluginInfoProto) -> PluginInfo: if proto.name == "": raise ValueError("name of PluginInfo does not exist or is empty inside the protobuf.") elif proto.version == "": raise ValueErro...
You are a Python code generator, capable of creating scripts from specifications.
def to_protobuf(self) -> PluginInfoProto: """ Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.PluginInfoProto """ proto = PluginInfoProto() proto.name = self.name proto.version = str(self.version) p...
Implement a Python 3 function for creating protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.PluginInfoProto
You are a Python code architect, reviewing and designing scalable and efficient code
Constructs a SaveState from a SaveState protobuf.
Can you generate the documentation for the following Python 3 function def from_protobuf(cls, proto: SaveStateProto) -> SaveState: data_dict = {} for key, link_item in proto.data.items(): data_dict[key] = LinkItem.from_protobuf(link_item) if proto.version == "": raise Val...
As a python code expert, you are capable of creating scripts from specifications.
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto
Make a summary of the following Python 3 code def to_protobuf(self) -> SaveStateProto: result = SaveStateProto() result.version = str(self.version) result.last_update.CopyFrom(datetime_to_timestamp(self.last_update)) result.plugin_info.CopyFrom(self.plugin_info.to_protobuf()) for...
As a Python code composer, you craft elegant and concise scripts.
def definite_article(word, gender=MALE, role=SUBJECT): """ Returns the definite article (der/die/das/die) for a given word. """ return article_definite.get((gender[:1].lower(), role[:3].lower()))
Implement a Python 3 function for returning the definite article for a given word.
As a Python code composer, you craft elegant and concise scripts.
Returns the indefinite article for a given word.
Can you generate the documentation for the following Python 3 function def indefinite_article(word, gender=MALE, role=SUBJECT): return article_indefinite.get((gender[:1].lower(), role[:3].lower()))
As a Python code composer, you craft elegant and concise scripts.
def article(word, function=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns the indefinite (ein) or definite (der/die/das/die) article for the given word. """ return function == DEFINITE \ and definite_article(word, gender, role) \ or indefinite_article(word, gender, role)
How would you implement a function in Python 3 that returns the indefinite or definite article for the given word.
You are a Python code analyst, evaluating scripts for potential improvements.
def referenced(word, article=INDEFINITE, gender=MALE, role=SUBJECT): """ Returns a string with the article + the word. """ return "%s %s" % (_article(word, article, gender, role), word)
Write a Python 3 function that can return a string with the article + the word.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the gender of the given word.
Given the following Python 3 function, write the documentation def gender(word, pos=NOUN): w = word.lower() if pos == NOUN: # Default rules (baseline = 32%). if w.endswith(gender_masculine): return MASCULINE if w.endswith(gender_feminine): return FEMININE ...
You are a Python code analyst, evaluating scripts for potential improvements.
def pluralize(word, pos=NOUN, gender=MALE, role=SUBJECT, custom={}): """ Returns the plural of a given word. The inflection is based on probability rather than gender and role. """ w = word.lower().capitalize() if word in custom: return custom[word] if pos == NOUN: for a, b i...
Write a Python 3 script for returning the plural of a given word.
As a python code expert, you are capable of creating scripts from specifications.
Returns the singular of a given word.
Make a summary of the following Python 3 code def singularize(word, pos=NOUN, gender=MALE, role=SUBJECT, custom={}): w = word.lower().capitalize() if word in custom: return custom[word] if word in singular: return singular[word] if pos == NOUN: for a, b in singular_inflections: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the attributive for the given adjective.
Given the following Python 3 function, write the documentation def attributive(adjective, gender=MALE, role=SUBJECT, article=None): w, g, c, a = \ adjective.lower(), gender[:1].lower(), role[:3].lower(), article and article.lower() or None if w in adjective_attributive: return adjective_attribut...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the predicative adjective.
Can you generate the documentation for the following Python 3 function def predicative(adjective): w = adjective.lower() if len(w) > 3: for suffix in ("em", "en", "er", "es", "e"): if w.endswith(suffix): b = w[:max(-len(suffix), -(len(w)-3))] if b.endswith("bl...
As a Python code analyst, you investigate and solve complex coding mysteries
def grade(adjective, suffix=COMPARATIVE): """ Returns the comparative or superlative form of the given (inflected) adjective. """ b = predicative(adjective) # groß => großt, schön => schönst if suffix == SUPERLATIVE and b.endswith(("s", u"ß")): suffix = suffix[1:] # große => großere, sch...
Write a Python 3 function for returning the comparative or superlative form of the given adjective.
As a Python code analyst, you investigate and solve complex coding mysteries
def find_lemma(self, verb): """ Returns the base form of the given inflected verb, using a rule-based approach. """ v = verb.lower() # Common prefixes: be-finden and emp-finden probably inflect like finden. if not (v.startswith("ge") and v.endswith("t")): # Probably gerund. ...
Can you write a function in Python 3 where it finds the base form of the given verb.
As a Python code analyst, you investigate and solve complex coding mysteries
def find_lexeme(self, verb): """ For a regular verb (base form), returns the forms using a rule-based approach. """ v = verb.lower() # Stem = infinitive minus -en, -ln, -rn. b = b0 = re.sub("en$", "", re.sub("ln$", "l", re.sub("rn$", "r", v))) # Split common prefixes. ...
Can you create a Python 3 function that finds the lexeme of a verb.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list of possible tenses for the given verb.
Make a summary of the following Python 3 code def tenses(self, verb, parse=True): tenses = _Verbs.tenses(self, verb, parse) if len(tenses) == 0: # auswirkte => wirkte aus for prefix in prefix_separable: if verb.startswith(prefix): tenses = _Ver...
You are a Python code analyst, evaluating scripts for potential improvements.
Return a set of all words in a dataset.
Can you generate a brief explanation for the following Python 3 code def _get_words_from_dataset(dataset): # Words may be either a string or a list of tokens. Return an iterator # of tokens accordingly def tokenize(words): if isinstance(words, basestring): return word_tokenize(words, inc...
You are a Python code analyst, evaluating scripts for potential improvements.
A basic document feature extractor that returns a dict indicating what words in train_set are contained in document.
How would you explain what the following Python 3 function does def basic_extractor(document, train_set): word_features = _get_words_from_dataset(train_set) tokens = _get_document_tokens(document) features = dict(((u'contains({0})'.format(word), (word in tokens)) for word in word_featur...
As a Python code translator, you convert algorithms and pseudocode into Python.
Reads a data file and returns and iterable that can be used as testing or training data.
Can you generate the documentation for the following Python 3 function def _read_data(self, dataset, format=None): # Attempt to detect file format if "format" isn't specified if not format: format_class = formats.detect(dataset) else: if format not in formats.AVAILABLE.ke...
As a Python code translator, you convert algorithms and pseudocode into Python.
Extracts features from a body of text.
Given the following Python 3 function, write the documentation def extract_features(self, text): # Feature extractor may take one or two arguments try: return self.feature_extractor(text, self.train_set) except (TypeError, AttributeError): return self.feature_extractor(te...
As a Python code translator, you convert algorithms and pseudocode into Python.
Train the classifier with a labeled feature set and return the classifier. Takes the same arguments as the wrapped NLTK class and returns the classifier.
Explain what the following Python 3 code does def train(self, *args, **kwargs): try: self.classifier = self.nltk_class.train(self.train_features, *args, **kwargs) return self.classifier except AttributeError: raise V...
As a Python code composer, you craft elegant and concise scripts.
def classify(self, text): """Classifies the text. :param str text: A string of text. """ text_features = self.extract_features(text) return self.classifier.classify(text_features)
Write a Python 3 script to classify the text. :param str text: A string of text.
You are a Python code analyst, evaluating scripts for potential improvements.
def accuracy(self, test_set, format=None): """Compute the accuracy on a test set. :param test_set: A list of tuples of the form ``(text, label)``, or a filename. :param format: If ``test_set`` is a filename, the file format, e.g. ``"csv"`` or ``"json"``. If ``None``, wil...
Can you create a Python 3 function that computes the accuracy on a test set.
As a python code expert, you are capable of creating scripts from specifications.
Update the classifier with new training data and re - traains the nltk_class.
Here you have a function in Python 3, explain what it does def update(self, new_data, *args, **kwargs): '''Update the classifier with new training data and re-trains the classifier. :param new_data: New data as a list of tuples of the form ``(text, label)``. ''' self...
As a Python code composer, you craft elegant and concise scripts.
Return the label probability distribution for classifying a string of text.
Make a summary of the following Python 3 code def prob_classify(self, text): text_features = self.extract_features(text) return self.classifier.prob_classify(text_features)
As a Python code translator, you convert algorithms and pseudocode into Python.
Train the classifier with a labeled and unlabeled feature sets and return the classifier. Takes the same arguments as the wrapped NLTK class and kwargs are passed to the wrapped NLTK class.
Can you tell what is the following Python 3 function doing def train(self, *args, **kwargs): self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the classifier with new data and re - traains the nltk_classifier.
Explain what the following Python 3 code does def update(self, new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs): '''Update the classifier with new data and re-trains the classifier. :param new_positive_data: List of new, la...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the label probability distribution for classifying a string of text.
Can you generate the documentation for the following Python 3 function def prob_classify(self, text): feats = self.extract_features(text) return self.classifier.prob_classify(feats)
As a Python code analyst, you investigate and solve complex coding mysteries
def lemmatize(self, text): """Return a list of (lemma, tag) tuples. :param str text: A string. """ #: Do not process empty strings (Issue #3) if text.strip() == "": return [] parsed_sentences = self._parse_text(text) _lemmalist = [] for s in ...
Write a Python 3 function that can return a list of tuples that are the lemma and tag.
You are a Python code generator, capable of creating scripts from specifications.
def _parse_text(self, text): """Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/LEMMA (separated by a forward slash '/') :param...
Implement a Python 3 function for parsing a string and return a list of parsed sentences.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns True if the pattern matches the given word string.
Explain what the following Python 3 code does def _match(string, pattern): p = pattern try: if p[:1] == WILDCARD and (p[-1:] == WILDCARD and p[1:-1] in string or string.endswith(p[1:])): return True if p[-1:] == WILDCARD and not p[-2:-1] == "\\" and string.startswith(p[:-1]): ...
As a python code expert, you are capable of creating scripts from specifications.
def unique(iterable): """ Returns a list copy in which each item occurs only once (in-order). """ seen = set() return [x for x in iterable if x not in seen and not seen.add(x)]
Implement a Python 3 function for returning a list of unique items in the iterable.
As a Python code translator, you convert algorithms and pseudocode into Python.
Yields all permutations with replacement
Given the following Python 3 function, write the documentation def product(*args, **kwargs): p = [[]] for iterable in map(tuple, args) * kwargs.get("repeat", 1): p = [x + [y] for x in p for y in iterable] for p in p: yield tuple(p)
As a Python code analyst, you investigate and solve complex coding mysteries
def variations(iterable, optional=lambda x: False): """ Returns all possible variations of a sequence with optional items. """ # For example: variations(["A?", "B?", "C"], optional=lambda s: s.endswith("?")) # defines a sequence where constraint A and B are optional: # [("A?", "B?", "C"), ("B?", "C"...
Can you write a function in Python 3 where it returns all possible variations of a sequence with optional items.
You are a Python code architect, reviewing and designing scalable and efficient code
def compile(pattern, *args, **kwargs): """ Returns a Pattern from the given string or regular expression. Recently compiled patterns are kept in cache (if they do not use taxonomies, which are mutable dicts). """ id, p = repr(pattern) + repr(args), pattern if id in _cache and not kwargs:...
Can you create a Python 3 function that returns a Pattern object from the given string or regular expression.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns True if pattern. search ( string ) may yield matches.
Can you generate a brief explanation for the following Python 3 code def scan(pattern, string, *args, **kwargs): return compile(pattern, *args, **kwargs).scan(string)
As a Python code composer, you craft elegant and concise scripts.
def match(pattern, sentence, *args, **kwargs): """ Returns the first match found in the given sentence, or None. """ return compile(pattern, *args, **kwargs).match(sentence)
Can you create a Python 3 function that matches a pattern against a given sentence.
As a python code expert, you are capable of creating scripts from specifications.
def search(pattern, sentence, *args, **kwargs): """ Returns a list of all matches found in the given sentence. """ return compile(pattern, *args, **kwargs).search(sentence)
How would you code a function in Python 3 to search for all matches in the given sentence.
You are a Python code analyst, evaluating scripts for potential improvements.
Adds a new item from the given key - value - tuple.
Here you have a function in Python 3, explain what it does def push(self, kv): if kv[0] in self: self.__delitem__(kv[0]) self.__setitem__(kv[0], kv[1])
As a python code expert, you are capable of creating scripts from specifications.
Appends the given term to the taxonomy and tags it as the given type.
Can you generate a brief explanation for the following Python 3 code def append(self, term, type=None, value=None): term = self._normalize(term) type = self._normalize(type) self.setdefault(term, (odict(), odict()))[0].push((type, True)) self.setdefault(type, (odict(), odict()))[1].push(...
You are a Python code generator, capable of creating scripts from specifications.
Returns the most recently added semantic type for the given term.
How would you explain what the following Python 3 function does def classify(self, term, **kwargs): term = self._normalize(term) if dict.__contains__(self, term): return self[term][0].keys()[-1] # If the term is not in the dictionary, check the classifiers. # Returns the firs...
As a Python code composer, you craft elegant and concise scripts.
def parents(self, term, recursive=False, **kwargs): """ Returns a list of all semantic types for the given term. If recursive=True, traverses parents up to the root. """ def dfs(term, recursive=False, visited={}, **kwargs): if term in visited: # Break on cyclic relations....
How would you code a function in Python 3 to return a list of all semantic types for the given term. If recursive = True traverses parents up to the root.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the value of the given term.
Explain what the following Python 3 code does def value(self, term, **kwargs): term = self._normalize(term) if term in self._values: return self._values[term] for classifier in self.classifiers: v = classifier.value(term, **kwargs) if v is not None: ...
As a python code expert, you are capable of creating scripts from specifications.
def fromstring(cls, s, **kwargs): """ Returns a new Constraint from the given string. Uppercase words indicate either a tag ("NN", "JJ", "VP") or a taxonomy term (e.g., "PRODUCT", "PERSON"). Syntax: ( defines an optional constraint, e.g., "(JJ)". [ def...
Implement a Python 3 function for parsing a string containing a set of constraints.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if the given word is part of the constraint False otherwise.
How would you explain what the following Python 3 function does def match(self, word): # If the constraint has a custom function it must return True. if self.custom is not None and self.custom(word) is False: return False # If the constraint can only match the first word, Word.index ...
As a python code expert, you are capable of creating scripts from specifications.
def fromstring(cls, s, *args, **kwargs): """ Returns a new Pattern from the given string. Constraints are separated by a space. If a constraint contains a space, it must be wrapped in []. """ s = s.replace("\(", "&lparen;") s = s.replace("\)", "&rparen;") ...
Can you write a function in Python 3 where it returns a new Pattern from the given string.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if search ( Sentence ( string ) may yield matches.
Can you generate a brief explanation for the following Python 3 code def scan(self, string): # In the following example, first scan the string for "good" and "bad": # p = Pattern.fromstring("good|bad NN") # for s in open("parsed.txt"): # if p.scan(s): # s = Sentence(s...
As a Python code translator, you convert algorithms and pseudocode into Python.
def search(self, sentence): """ Returns a list of all matches found in the given sentence. """ if sentence.__class__.__name__ == "Sentence": pass elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text": a=[]; [a.extend(self.search(s)) for s in sen...
Implement a function in Python 3 to return a list of all matches found in the given sentence.
You are a Python code generator, capable of creating scripts from specifications.
def match(self, sentence, start=0, _v=None, _u=None): """ Returns the first match found in the given sentence, or None. """ if sentence.__class__.__name__ == "Sentence": pass elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text": return find(lam...
Implement a Python 3 function for returning the first match found in the given sentence or None.
You are a Python code generator, capable of creating scripts from specifications.
Returns the constraint that matches the given Word or None if no constraint is found.
Can you generate the documentation for the following Python 3 function def constraint(self, word): if word.index in self._map1: return self._map1[word.index]
As a Python code composer, you craft elegant and concise scripts.
def constraints(self, chunk): """ Returns a list of constraints that match the given Chunk. """ a = [self._map1[w.index] for w in chunk.words if w.index in self._map1] b = []; [b.append(constraint) for constraint in a if constraint not in b] return b
Write a Python 3 script for returning a list of constraints that match the given Chunk.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a list of Word and Chunk objects where words have been grouped into their chunks whenever possible. Optionally returns only chunks and words that match given constraint.
How would you explain what the following Python 3 function does def constituents(self, constraint=None): # Select only words that match the given constraint. # Note: this will only work with constraints from Match.pattern.sequence. W = self.words n = len(self.pattern.sequence) if...
As a Python code translator, you convert algorithms and pseudocode into Python.
def group(self, index, chunked=False): """ Returns a list of Word objects that match the given group. With chunked=True, returns a list of Word + Chunk objects - see Match.constituents(). A group consists of consecutive constraints wrapped in { }, e.g., search("{JJ JJ} NN", S...
Can you create a Python 3 function that returns a list of Word objects that match the given group.
As a Python code composer, you craft elegant and concise scripts.
Return the sentiment as a tuple of the form polarity subjectivity
Can you tell what is the following Python 3 function doing def analyze(self, text): if self.lemmatize: text = self._lemmatize(text) return self.RETURN_TYPE(*pattern_sentiment(text))
As a python code expert, you are capable of creating scripts from specifications.
def stts2universal(token, tag): """ Converts an STTS tag to a universal tag. For example: ohne/APPR => ohne/PREP """ if tag in ("KON", "KOUI", "KOUS", "KOKOM"): return (token, CONJ) if tag in ("PTKZU", "PTKNEG", "PTKVZ", "PTKANT"): return (token, PRT) if tag in ("PDF", "PDAT"...
Create a Python 3 function to convert an STTS tag to a universal tag.
As a python code expert, you are capable of creating scripts from specifications.
Annotates the tokens with lemmata for plural nouns and conjugated verbs and where each token is a [ word part - of - speech list.
Here you have a function in Python 3, explain what it does def find_lemmata(tokens): for token in tokens: word, pos, lemma = token[0], token[1], token[0] if pos.startswith(("DT", "JJ")): lemma = predicative(word) if pos == "NNS": lemma = singularize(word) if...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a parsed Text from the given parsed string.
How would you explain what the following Python 3 function does def tree(s, token=[WORD, POS, CHUNK, PNP, REL, LEMMA]): return Text(s, token)
As a Python code composer, you craft elegant and concise scripts.
Returns a list of ( token tag ) - tuples from the given string.
Given the following Python 3 function, write the documentation def tag(s, tokenize=True, encoding="utf-8", **kwargs): tags = [] for sentence in parse(s, tokenize, True, False, False, False, encoding, **kwargs).split(): for token in sentence: tags.append((token[0], token[1])) return tags
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a sorted list of keywords in the given string.
Make a summary of the following Python 3 code def keywords(s, top=10, **kwargs): return parser.find_keywords(s, top=top, frequency=parser.frequency)
As a python code expert, you are capable of creating scripts from specifications.
Tokenize a string of text into a list of word tokens.
Can you generate the documentation for the following Python 3 function def tokenize(self, text, include_punc=True, nested=False): self.tokens = [ w for w in ( self.word_tokenize( s, include_punc) for s in self.sent_tokenize(text))] if n...
You are a Python code analyst, evaluating scripts for potential improvements.
Tokenizes a text into sentences.
Here you have a function in Python 3, explain what it does def sent_tokenize(self, text, **kwargs): sentences = self.sent_tok.tokenize( text, realign_boundaries=kwargs.get( "realign_boundaries", True)) return sentences
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of sentences that are sent to the given text.
Can you generate a brief explanation for the following Python 3 code def sent_tokenize(self, text, **kwargs): sentences = find_sentences(text, punctuation=kwargs.get( "punctuation", PUNCTUATION), ...
As a Python code analyst, you investigate and solve complex coding mysteries
Tokenize a string of text into a list of word tokens.
Can you generate the documentation for the following Python 3 function def tokenize(self, text, include_punc=True, **kwargs): return self.tokenizer.word_tokenize(text, include_punc, **kwargs)
You are a Python code generator, capable of creating scripts from specifications.
Parses the text and returns a dictionary of the related attributes.
Can you generate a brief explanation for the following Python 3 code def parse(self, text): #: Do not process empty strings (Issue #3) if text.strip() == "": return "" #: Do not process strings consisting of a single punctuation mark (Issue #4) elif text.strip() in PUNCTUATIO...
As a Python code composer, you craft elegant and concise scripts.
def extract(self, text): """Return a list of noun phrases (strings) for a body of text. :param str text: A string. """ _extracted = [] if text.strip() == "": return _extracted parsed_sentences = self._parse_text(text) for s in parsed_sentences: ...
Write a Python 3 function that can extract a list of noun phrases for a body of text.
You are a Python code generator, capable of creating scripts from specifications.
def _filter_extracted(self, extracted_list): """Filter insignificant words for key noun phrase extraction. determiners, relative pronouns, reflexive pronouns In general, pronouns are not useful, as you need context to know what they refer to. Most of the pronouns, however, are filtered ...
How would you code a function in Python 3 to filter insignificant words for key noun phrase extraction.
As a Python code composer, you craft elegant and concise scripts.
def _parse_text(self, text): """Parse text (string) and return list of parsed sentences (strings). Each sentence consists of space separated token elements and the token format returned by the PatternParser is WORD/TAG/PHRASE/ROLE/(LEMMA) (separated by a forward slash '/') :par...
Write a Python 3 script to parse text and return list of parsed sentences.
You are a Python code analyst, evaluating scripts for potential improvements.
Tag a string sentence.
How would you explain what the following Python 3 function does def tag(self, sentence, tokenize=True): #: Do not process empty strings (Issue #3) if sentence.strip() == "": return [] #: Do not process strings consisting of a single punctuation mark (Issue #4) elif sentence.s...
As a Python code composer, you craft elegant and concise scripts.
Returns the given value as a Unicode string ( if possible ).
Can you generate a brief explanation for the following Python 3 code def decode_string(v, encoding="utf-8"): if isinstance(encoding, basestring): encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore")) if isinstance(v, binary_type): for e in encoding: try: ...
As a Python code composer, you craft elegant and concise scripts.
def encode_string(v, encoding="utf-8"): """Returns the given value as a Python byte string (if possible).""" if isinstance(encoding, basestring): encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore")) if isinstance(v, unicode): for e in encoding: try: ...
Can you implement a function in Python 3 that returns the given value as a Python byte string ( if possible.
As a python code expert, you are capable of creating scripts from specifications.
Returns the path which conforms to the given command mode and a PATH string.
Here you have a function in Python 3, explain what it does def _shutil_which(cmd, mode=os.F_OK | os.X_OK, path=None): # Check that a given file can be accessed with the correct mode. # Additionally check that `file` is not a directory, as on Windows # directories pass the os.access check. def _access_ch...
As a Python code composer, you craft elegant and concise scripts.
Translate the word to another language using Google s Translate API.
Can you tell what is the following Python 3 function doing def translate(self, from_lang=None, to="de"): if from_lang is None: from_lang = self.translator.detect(self.string) return self.translator.translate(self.string, from_lang=from_lang, to_lang=t...
You are a Python code generator, capable of creating scripts from specifications.
Return the lemma of each word in this WordList. This method uses NLTKPunktTokenizer to get all lemmatization results for all words in this WordList.
Here you have a function in Python 3, explain what it does def lemmatize(self): _lemmatizer = PatternParserLemmatizer(tokenizer=NLTKPunktTokenizer()) # WordList object --> Sentence.string # add a period (improves parser accuracy) _raw = " ".join(self) + "." _lemmas = _lemmatizer....
You are a Python code generator, capable of creating scripts from specifications.
Return a list of tokens using tokenizer.
Make a summary of the following Python 3 code def tokenize(self, tokenizer=None): t = tokenizer if tokenizer is not None else self.tokenizer return WordList(t.tokenize(self.raw))
You are a Python code analyst, evaluating scripts for potential improvements.
def noun_phrases(self): """Returns a list of noun phrases for this blob.""" return WordList([phrase.strip() for phrase in self.np_extractor.extract(self.raw) if len(phrase.split()) > 1])
Implement a Python 3 function for returning a list of noun phrases for this blob.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of tuples of the form word POS tag.
Explain what the following Python 3 code does def pos_tags(self): return [(Word(word, pos_tag=t), unicode(t)) for word, t in self.pos_tagger.tag(self.raw) # new keyword PatternTagger(include_punc=False) # if not PUNCTUATION_REGEX.match(unicode(t)) ...
As a Python code composer, you craft elegant and concise scripts.
The dict representation of this sentence.
Make a summary of the following Python 3 code def dict(self): return { 'raw': self.raw, 'start_index': self.start_index, 'end_index': self.end_index, 'stripped': self.stripped, 'noun_phrases': self.noun_phrases, 'polarity': self.polarity, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def words(self): """Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the ``tokens`` property. :returns: A :class:`WordList <WordList>` of word tokens. """ return WordList( word_tokenize...
Write a Python 3 function for returning a list of word tokens. This excludes punctuation characters.
You are a Python code generator, capable of creating scripts from specifications.
Return a namedtuple containing the polarity and subjectivity of the current object.
Can you tell what is the following Python 3 function doing def sentiment(self): #: Enhancement Issue #2 #: adapted from 'textblob.en.sentiments.py' #: Return type declaration _RETURN_TYPE = namedtuple('Sentiment', ['polarity', 'subjectivity']) _polarity = 0 _subjectivity ...
As a python code expert, you are capable of creating scripts from specifications.
Return a json representation of this blob. Takes the same arguments as json. dumps.
How would you explain what the following Python 3 function does def to_json(self, *args, **kwargs): return json.dumps(self.serialized, *args, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a list of Sentence objects from the raw text.
Can you tell what is the following Python 3 function doing def _create_sentence_objects(self): sentence_objects = [] sentences = sent_tokenize(self.raw, tokenizer=self.tokenizer) char_index = 0 # Keeps track of character index within the blob for sent in sentences: # Compute...
You are a Python code generator, capable of creating scripts from specifications.
def ngrams(string, n=3, punctuation=PUNCTUATION, continuous=False): """ Returns a list of n-grams (tuples of n successive words) from the given string. Alternatively, you can supply a Text or Sentence object. With continuous=False, n-grams will not run over sentence markers (i.e., .!?). Punc...
Implement a function in Python 3 to return a list of n - grams from the given string.
As a Python code analyst, you investigate and solve complex coding mysteries
def deflood(s, n=3): """ Returns the string with no more than n repeated characters, e.g., deflood("NIIIICE!!", n=1) => "Nice!" deflood("nice.....", n=3) => "nice..." """ if n == 0: return s[0:0] return re.sub(r"((.)\2{%s,})" % (n-1), lambda m: m.group(1)[0] * n, s)
Can you write a function in Python 3 where it returns a string with no more than n repeated characters.
You are a Python code generator, capable of creating scripts from specifications.
Pretty - prints the output of Parser. parse as a table with outlined columns.
Can you generate a brief explanation for the following Python 3 code def pprint(string, token=[WORD, POS, CHUNK, PNP], column=4): if isinstance(string, basestring): print("\n\n".join([table(sentence, fill=column) for sentence in Text(string, token)])) if isinstance(string, Text): print("\n\n".jo...
As a python code expert, you are capable of creating scripts from specifications.
def _read(path, encoding="utf-8", comment=";;;"): """ Returns an iterator over the lines in the file at the given path, strippping comments and decoding each line to Unicode. """ if path: if isinstance(path, basestring) and os.path.exists(path): # From file path. if P...
Can you create a Python 3 function that reads the file at the given path and returns an iterator over the lines in the file at the given path stripping comments and decoding each line to Unicode.
You are a Python code generator, capable of creating scripts from specifications.
Returns a tuple with a simplified universal part - of - speech tag.
Can you tell what is the following Python 3 function doing def penntreebank2universal(token, tag): if tag.startswith(("NNP-", "NNPS-")): return (token, "%s-%s" % (NOUN, tag.split("-")[-1])) if tag in ("NN", "NNS", "NNP", "NNPS", "NP"): return (token, NOUN) if tag in ("MD", "VB", "VBD", "VBG"...
You are a Python code architect, reviewing and designing scalable and efficient code
Find all tokens in a string.
Can you tell what is the following Python 3 function doing def find_tokens(string, punctuation=PUNCTUATION, abbreviations=ABBREVIATIONS, replace=replacements, linebreak=r"\n{2,}"): # Handle periods separately. punctuation = tuple(punctuation.replace(".", "")) # Handle replacements (contractions). for a,...
As a python code expert, you are capable of creating scripts from specifications.
def _suffix_rules(token, tag="NN"): """ Default morphological tagging rules for English, based on word suffixes. """ if isinstance(token, (list, tuple)): token, tag = token if token.endswith("ing"): tag = "VBG" if token.endswith("ly"): tag = "RB" if token.endswith("s") an...
Create a Python 3 function to default morphological tagging rules for English based on word suffixes.
You are a Python code architect, reviewing and designing scalable and efficient code
Find tags for a list of tokens.
Can you generate a brief explanation for the following Python 3 code def find_tags(tokens, lexicon={}, model=None, morphology=None, context=None, entities=None, default=("NN", "NNP", "CD"), language="en", map=None, **kwargs): tagged = [] # Tag known words. for i, token in enumerate(tokens): tagged.a...
As a python code expert, you are capable of creating scripts from specifications.
def find_chunks(tagged, language="en"): """ The input is a list of [token, tag]-items. The output is a list of [token, tag, chunk]-items: The/DT nice/JJ fish/NN is/VBZ dead/JJ ./. => The/DT/B-NP nice/JJ/I-NP fish/NN/I-NP is/VBZ/B-VP dead/JJ/B-ADJP ././O """ chunked = [x for x in tagg...
Create a Python 3 function to find the chunks of a given language.
As a Python code analyst, you investigate and solve complex coding mysteries
def find_prepositions(chunked): """ The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. """ # Tokens that are not part of a preposition just get the O-tag. for ch in chunked...
Can you write a function in Python 3 where it finds prepositions of the items in a list of tokens.
As a python code expert, you are capable of creating scripts from specifications.
This function finds the relation between two noun phrase tokens and a list of tokens.
Can you generate the documentation for the following Python 3 function def find_relations(chunked): tag = lambda token: token[2].split("-")[-1] # B-NP => NP # Group successive tokens with the same chunk-tag. chunks = [] for token in chunked: if len(chunks) == 0 \ or token[2].startswith("...
As a Python code analyst, you investigate and solve complex coding mysteries
def find_keywords(string, parser, top=10, frequency={}, **kwargs): """ Returns a sorted list of keywords in the given string. The given parser (e.g., pattern.en.parser) is used to identify noun phrases. The given frequency dictionary can be a reference corpus, with relative document frequenc...
Write a Python 3 function for returning a sorted list of keywords in the given string.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the tense id for a given set of parameters.
Make a summary of the following Python 3 code def tense_id(*args, **kwargs): # Unpack tense given as a tuple, e.g., tense((PRESENT, 1, SG)): if len(args) == 1 and isinstance(args[0], (list, tuple)): if args[0] not in ((PRESENT, PARTICIPLE), (PAST, PARTICIPLE)): args = args[0] # No para...
As a Python code composer, you craft elegant and concise scripts.
def _multilingual(function, *args, **kwargs): """ Returns the value from the function with the given name in the given language module. By default, language="en". """ return getattr(_module(kwargs.pop("language", "en")), function)(*args, **kwargs)
Implement a Python 3 function for returning the value of the given function in the given language module.
As a python code expert, you are capable of creating scripts from specifications.
def language(s): """ Returns a (language, confidence)-tuple for the given string. """ s = decode_utf8(s) s = set(w.strip(PUNCTUATION) for w in s.replace("'", "' ").split()) n = float(len(s) or 1) p = {} for xx in LANGUAGES: lexicon = _module(xx).__dict__["lexicon"] p[xx] = su...
Write a Python 3 function that can return a tuple of language and confidence for the given string.
You are a Python code architect, reviewing and designing scalable and efficient code
Wrapper for lazylist. method.
Explain what the following Python 3 code does def _lazy(self, method, *args): if list.__len__(self) == 0: self.load() setattr(self, method, types.MethodType(getattr(list, method), self)) return getattr(list, method)(self, *args)
You are a Python code analyst, evaluating scripts for potential improvements.
def train(self, token, tag, previous=None, next=None): """ Trains the model to predict the given tag for the given token, in context of the given previous and next (token, tag)-tuples. """ self._classifier.train(self._v(token, previous, next), type=tag)
Create a Python 3 function to train the model to predict the given tag for the given token.
As a python code expert, you are capable of creating scripts from specifications.