Search is not available for this dataset
text
stringlengths
75
104k
def document_frequencies(self, hashes): '''Get document frequencies for a list of hashes. This will return all zeros unless the index was written with `hash_frequencies` set. If :data:`DOCUMENT_HASH_KEY` is included in `hashes`, that value will be returned with the total number...
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a ...
def lookup_tf(self, h): '''Get stream IDs and term frequencies for a single hash. This yields pairs of strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item` and the corresponding term frequency. ..see:: :meth:`lookup` ''' ...
def _make_stream_items(f): """Given a spinn3r feed, produce a sequence of valid StreamItems. Because of goopy Python interactions, you probably need to call this and re-yield its results, as >>> with open(filename, 'rb') as f: ... for si in _make_stream_items(f): ... yield si """ ...
def _make_stream_item(entry): """Given a single spinn3r feed entry, produce a single StreamItem. Returns 'None' if a complete item can't be constructed. """ # get standard metadata, assuming it's present... if not hasattr(entry, 'permalink_entry'): return None pe = entry.permalink_entr...
def _make_content_item(node, mime_type=None, alternate_data=None): """Create a ContentItem from a node in the spinn3r data tree. The ContentItem is created with raw data set to ``node.data``, decompressed if the node's encoding is 'zlib', and UTF-8 normalized, with a MIME type from ``node.mime_type``. ...
def _read(self, n): """Read (up to) 'n' bytes from the underlying file. If any bytes have been pushed in with _unread() those are returned first.""" if n <= len(self._prefix): # the read can be fulfilled entirely from the prefix result = self._prefix[:n] self...
def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) return n
def _read_a(self, cls): """Read some protobuf-encoded object stored in a single block out of the file.""" o = cls() o.ParseFromString(self._read_block()) return o
def parse_keys_and_ranges(i_str, keyfunc, rangefunc): '''Parse the :class:`from_kvlayer` input string. This accepts two formats. In the textual format, it accepts any number of stream IDs in timestamp-docid format, separated by ``,`` or ``;``, and processes those as individual stream IDs. In the ...
def get_kvlayer_stream_item(client, stream_id): '''Retrieve a :class:`streamcorpus.StreamItem` from :mod:`kvlayer`. This function requires that `client` already be set up properly:: client = kvlayer.client() client.setup_namespace(STREAM_ITEM_TABLE_DEFS, STREAM_I...
def make_doc_id_range(doc_id): '''Construct a tuple(begin, end) of one-tuple kvlayer keys from a hexdigest doc_id. ''' assert len(doc_id) == 32, 'expecting 32 hex string, not: %r' % doc_id bin_docid = base64.b16decode(doc_id.upper()) doc_id_range = ((bin_docid,), (bin_docid,)) return doc_id...
def get_kvlayer_stream_item_by_doc_id(client, doc_id): '''Retrieve :class:`streamcorpus.StreamItem`s from :mod:`kvlayer`. Namely, it returns an iterator over all documents with the given docid. The docid should be an md5 hash of the document's abs_url. :param client: kvlayer client object :type cl...
def get_kvlayer_stream_ids_by_doc_id(client, doc_id): '''Retrieve stream ids from :mod:`kvlayer`. Namely, it returns an iterator over all stream ids with the given docid. The docid should be an md5 hash of the document's abs_url. :param client: kvlayer client object :type client: :class:`kvlayer.A...
def serialize_si_key(si_key): ''' Return packed bytes representation of StreamItem kvlayer key. The result is 20 bytes, 16 of md5 hash, 4 of int timestamp. ''' if len(si_key[0]) != 16: raise ValueError('bad StreamItem key, expected 16 byte ' 'md5 hash binary digest, ...
def streamitem_to_key_data(si): ''' extract the parts of a StreamItem that go into a kvlayer key, convert StreamItem to blob for storage. return (kvlayer key tuple), data blob ''' key = key_for_stream_item(si) data = streamcorpus.serialize(si) errors, data = streamcorpus.compress_and_en...
def working_directory(path): """Change working directory and restore the previous on exit""" prev_dir = os.getcwd() os.chdir(str(path)) try: yield finally: os.chdir(prev_dir)
def strip_prefix(s, prefix, strict=False): """Removes the prefix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the prefix was present""" if s.startswith(prefix): return s[len(prefix) :] elif strict: raise WimpyError("string doesn't start with p...
def strip_suffix(s, suffix, strict=False): """Removes the suffix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the suffix was present""" if s.endswith(suffix): return s[: len(s) - len(suffix)] elif strict: raise WimpyError("string doesn't end w...
def is_subsequence(needle, haystack): """Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout""" it = iter(haystack) for element in needle: if element not in it: return False return True
def cube(): """Return an Ice application with a default home page. Create :class:`Ice` object, add a route to return the default page when a client requests the server root, i.e. /, using HTTP GET method, add an error handler to return HTTP error pages when an error occurs and return this object. T...
def run(self, host='127.0.0.1', port=8080): """Run the application using a simple WSGI server. Arguments: host (str, optional): Host on which to listen. port (int, optional): Port number on which to listen. """ from wsgiref import simple_server self._server =...
def exit(self): """Stop the simple WSGI server running the appliation.""" if self._server is not None: self._server.shutdown() self._server.server_close() self._server = None
def route(self, method, pattern): """Decorator to add route for a request with any HTTP method. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. pattern (str): Routing pattern the path must match. Returns: function: Decorator function to add route. ...
def error(self, status=None): """Decorator to add a callback that generates error page. The *status* parameter specifies the HTTP response status code for which the decorated callback should be invoked. If the *status* argument is not specified, then the decorated callable is co...
def static(self, root, path, media_type=None, charset='UTF-8'): """Send content of a static file as response. The path to the document root directory should be specified as the root argument. This is very important to prevent directory traversal attack. This method guarantees that only ...
def download(self, content, filename=None, media_type=None, charset='UTF-8'): """Send content as attachment (downloadable file). The *content* is sent after setting Content-Disposition header such that the client prompts the user to save the content locally as a file. A...
def _get_error_page_callback(self): """Return an error page for the current response status.""" if self.response.status in self._error_handlers: return self._error_handlers[self.response.status] elif None in self._error_handlers: return self._error_handlers[None] ...
def add(self, method, pattern, callback): """Add a route. Arguments: method (str): HTTP method, e.g. GET, POST, etc. pattern (str): Pattern that request paths must match. callback (str): Route handler that is invoked when a request path matches the *pattern*. ...
def contains_method(self, method): """Check if there is at least one handler for *method*. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. Returns: ``True`` if there is at least one route defined for *method*, ``False`` otherwise """ ...
def resolve(self, method, path): """Resolve a request to a route handler. Arguments: method (str): HTTP method, e.g. GET, POST, etc. (type: str) path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) ...
def _resolve_non_literal_route(self, method, path): """Resolve a request to a wildcard or regex route handler. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. path (str): Request path Returns: tuple or None: A tuple of three items: 1. ...
def _normalize_pattern(pattern): """Return a normalized form of the pattern. Normalize the pattern by removing pattern type prefix if it exists in the pattern. Then return the pattern type and the pattern as a tuple of two strings. Arguments: pattern (str): Route patt...
def match(self, path): """Return route handler with arguments if path matches this route. Arguments: path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) 3. K...
def match(self, path): """Return route handler with arguments if path matches this route. Arguments: path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) 3. K...
def response(self): """Return the HTTP response body. Returns: bytes: HTTP response body as a sequence of bytes """ if isinstance(self.body, bytes): out = self.body elif isinstance(self.body, str): out = self.body.encode(self.charset) el...
def add_header(self, name, value): """Add an HTTP header to response object. Arguments: name (str): HTTP header field name value (str): HTTP header field value """ if value is not None: self._headers.append((name, value))
def set_cookie(self, name, value, attrs={}): """Add a Set-Cookie header to response object. For a description about cookie attribute values, see https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel. Arguments: name (str): Name of the cookie value ...
def status_line(self): """Return the HTTP response status line. The status line is determined from :attr:`status` code. For example, if the status code is 200, then '200 OK' is returned. Returns: str: Status line """ return (str(self.status) + ' ' + ...
def content_type(self): """Return the value of Content-Type header field. The value for the Content-Type header field is determined from the :attr:`media_type` and :attr:`charset` data attributes. Returns: str: Value of Content-Type header field """ if (self.m...
def getall(self, key, default=[]): """Return the list of all values for the specified key. Arguments: key (object): Key default (list): Default value to return if the key does not exist, defaults to ``[]``, i.e. an empty list. Returns: list: List of al...
def rmtree(path, use_shutil=True, followlinks=False, retries=10): '''remove all files and directories below path, including path itself; works even when shutil.rmtree fails because of read-only files in NFS and Windows. Follows symlinks. `use_shutil` defaults to True; useful for testing `followli...
def get_open_fds(verbose=False): '''return list of open files for current process .. warning: will only work on UNIX-like os-es. ''' pid = os.getpid() procs = subprocess.check_output( [ "lsof", '-w', '-Ff', "-p", str( pid ) ] ) if verbose: oprocs = subprocess.check_output( ...
def file_type_stats(config): ''' returns a kba.pipeline "transform" function that generates file type stats from the stream_items that it sees. Currently, these stats are just the first five non-whitespace characters. ''' ## make a closure around config def _file_type_stats(stream_item, con...
def rejester_run(work_unit): '''get a rejester.WorkUnit with KBA s3 path, fetch it, and save some counts about it. ''' #fname = 'verify-chunks-%d-%d' % (os.getpid(), time.time()) fname = work_unit.key.strip().split('/')[-1] output_dir_path = work_unit.data.get('output_dir_path', '/mn...
def attempt_fetch(work_unit, fpath): '''attempt a fetch and iteration over a work_unit.key path in s3 ''' url = 'http://s3.amazonaws.com/aws-publicdatasets/' + work_unit.key.strip() ## cheapest way to iterate over the corpus is a few stages of ## streamed child processes. Note that stderr nee...
def get_file_lines(file_name): """Return a list of non-empty lines from `file_path`.""" file_path = path.join(path.dirname(path.abspath(__file__)), file_name) with open(file_path) as file_obj: return [line for line in file_obj.read().splitlines() if line]
def get_describers(): """ Return a describer tuple in the form `(name, position)`, where position is either 'prefix' or 'suffix'. """ adjectives = map(lambda x: (x, 'prefix'), get_file_lines('adjectives.txt')) animal_nouns = map(lambda x: (x, 'suffix'), get_file_lines('nouns.txt')) return li...
def _random_adjspecies_pair(): """Return an ordered 2-tuple containing a species and a describer.""" describer, desc_position = random_describer() if desc_position == 'prefix': return (describer, random_species()) elif desc_position == 'suffix': return (random_species(), describer)
def random_adjspecies_pair(maxlen=None, prevent_stutter=True): """ Return an ordered 2-tuple containing a species and a describer. The letter-count of the pair is guarantee to not exceed `maxlen` if it is given. If `prevent_stutter` is True, the last letter of the first item of the pair will be diff...
def random_adjspecies(sep='', maxlen=8, prevent_stutter=True): """ Return a random adjective/species, separated by `sep`. The keyword arguments `maxlen` and `prevent_stutter` are the same as for `random_adjspecies_pair`, but note that the maximum length argument is not affected by the separator. ...
def morph(ctx, app_id, sentence_file, json_flag, sentence, info_filter, pos_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode, unicode) -> None # NOQA """ Morphological analysis for Japanese.""" app_id = clean_app_id(app_id) sentence = clean_senten...
def similarity(ctx, app_id, json_flag, query_pair, request_id): # type: (Context, unicode, bool, List[unicode], unicode) -> None """ Scoring the similarity of two words. """ app_id = clean_app_id(app_id) api = GoolabsAPI(app_id) ret = api.similarity( query_pair=query_pair, request_...
def hiragana(ctx, app_id, sentence_file, json_flag, sentence, output_type, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Convert the Japanese to Hiragana or Katakana. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sen...
def entity(ctx, app_id, sentence_file, json_flag, sentence, class_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Extract unique representation from sentence. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sentenc...
def shortsum(ctx, app_id, review_file, json_flag, review, length, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Summarize reviews into a short summary.""" app_id = clean_app_id(app_id) review_list = clean_review(review, review_file...
def keyword(ctx, app_id, body_file, json_flag, title, body, max_num, forcus, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, int, unicode, unicode) -> None # NOQA """Extract "keywords" from an input document. """ app_id = clean_app_id(app_id) body = clean_body(...
def chrono(ctx, app_id, sentence_file, json_flag, sentence, doc_time, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Extract expression expressing date and time and normalize its value """ app_id = clean_app_id(app_id) sentence = cle...
def create(self, stage, scp_config, config=None): '''Create a pipeline stage. Instantiates `stage` with `config`. This essentially translates to ``stage(config)``, except that two keys from `scp_config` are injected into the configuration: ``tmp_dir_path`` is an execution-speci...
def _init_stages(self, config, name): '''Create a list of indirect stages. `name` should be the name of a config item that holds a list of names of stages, for instance, ``writers``. This looks up the names of those stages, then creates and returns the corresponding list of sta...
def _init_all_stages(self, config): '''Create stages that are used for the pipeline. :param dict config: `streamcorpus_pipeline` configuration :return: tuple of (reader, incremental transforms, batch transforms, post-batch incremental transforms, writers, temporary directory...
def _process_task(self, work_unit): '''Process a :class:`coordinate.WorkUnit`. The work unit's key is taken as the input file name. The data should have ``start_count`` and ``start_chunk_time`` values, which are passed on to :meth:`run`. :param work_unit: work unit to process ...
def run(self, i_str, start_count=0, start_chunk_time=None): '''Run the pipeline. This runs all of the steps described in the pipeline constructor, reading from some input and writing to some output. :param str i_str: name of the input file, or other reader-specific descriptio...
def _process_output_chunk(self, start_count, next_idx, sources, i_str, t_path): ''' for the current output chunk (which should be open): 1. run batch transforms 2. run post-batch incremental transforms 3. run 'writers' to load-out the data to f...
def _run_writers(self, start_count, next_idx, sources, i_str, t_path): '''Run all of the writers over some intermediate chunk. :param int start_count: index of the first item :param int next_idx: index of the next item (after the last item in this chunk) :param list sources: s...
def _run_incremental_transforms(self, si, transforms): ''' Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None. ''' ## operate each transform on this one Strea...
def get_name_info(chunk_path, assert_one_date_hour=False, i_str=None, chunk_type=Chunk): ''' takes a chunk blob and obtains the date_hour, md5, num makes fields: i_str input_fname input_md5 - parsed from input filename if it contains '-%(md5)s-' md5 num epoch_ticks...
def replace_config(config, name): '''Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_...
def make_app(): """Make a WSGI app that has all the HTTPie pieces baked in.""" env = Environment() # STDIN is ignored because HTTPony runs a server that doesn't care. # Additionally, it is needed or else pytest blows up. args = parser.parse_args(args=['/', '--ignore-stdin'], env=env) args.output...
def make_chains_with_names(sentences): ''' assemble in-doc coref chains by mapping equiv_id to tokens and their cleansed name strings :param sentences: iterator over token generators :returns dict: keys are equiv_ids, values are tuple(concatentated name string, list of tokens) '...
def ALL_mentions(target_mentions, chain_mentions): ''' For each name string in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains the name. Returns True only if all of the target_mention strings appeared as substrings of at least one cle...
def ANY_MULTI_TOKEN_mentions(multi_token_target_mentions, chain_mentions): ''' For each name string (potentially consisting of multiple tokens) in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains all the tokens in the name. Returns Tru...
def ANY_mentions(target_mentions, chain_mentions): ''' For each name string in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains the name. Returns True if any of the target_mention strings appeared as substrings of any cleansed Token.to...
def names_in_chains(stream_item, aligner_data): ''' Convert doc-level Rating object into a Label, and add that Label to all Token in all coref chains identified by aligner_data["chain_selector"] :param stream_item: document that has a doc-level Rating to translate into token-level Labels. :para...
def look_ahead_match(rating, tokens): '''iterate through all tokens looking for matches of cleansed tokens or token regexes, skipping tokens left empty by cleansing and coping with Token objects that produce multiple space-separated strings when cleansed. Yields tokens that match. ''' ## this ...
def multi_token_match(stream_item, aligner_data): ''' iterate through tokens looking for near-exact matches to strings in si.ratings...mentions ''' tagger_id = _get_tagger_id(stream_item, aligner_data) sentences = stream_item.body.sentences.get(tagger_id) if not sentences: return...
def make_ner_file(self, clean_visible_path, ner_xml_path): '''run tagger a child process to get XML output''' if self.template is None: raise exceptions.NotImplementedError(''' Subclasses must specify a class property "template" that provides command string format for running a tagger. It s...
def align_chunk_with_ner(self, ner_xml_path, i_chunk, o_chunk): ''' iterate through ner_xml_path to fuse with i_chunk into o_chunk ''' ## prepare to iterate over the input chunk input_iter = i_chunk.__iter__() all_ner = xml.dom.minidom.parse(open(ner_xml_path)) ## this converts...
def shutdown(self): ''' send SIGTERM to the tagger child process ''' if self._child: try: self._child.terminate() except OSError, exc: if exc.errno == 3: ## child is already gone, possibly because it ran ...
def mult(p, n): """Returns a Pattern that matches exactly n repetitions of Pattern p. """ np = P() while n >= 1: if n % 2: np = np + p p = p + p n = n // 2 return np
def fix_emails(text): '''Replace all angle bracket emails with a unique key.''' emails = bracket_emails.findall(text) keys = [] for email in emails: _email = email.replace("<","&lt;").replace(">","&gt;") text = text.replace(email, _email) return text
def _sentences(self, clean_visible): 'generate strings identified as sentences' previous_end = 0 clean_visible = clean_visible.decode('utf8') for start, end in self.sentence_tokenizer.span_tokenize(clean_visible): # no need to check start, because the first byte of text ...
def make_label_index(self, stream_item): 'make a sortedcollection on body.labels' labels = stream_item.body.labels.get(self.annotator_id) if not labels: labels = [] self.label_index = SortedCollection( [l for l in labels if OffsetType.CHARS in l.offsets], ...
def make_sentences(self, stream_item): 'assemble Sentence and Token objects' self.make_label_index(stream_item) sentences = [] token_num = 0 new_mention_id = 0 for sent_start, sent_end, sent_str in self._sentences( stream_item.body.clean_visible): ...
def html_entities_to_unicode(text, space_padding=False, safe_only=False): ''' Convert any HTML, XML, or numeric entities in the attribute values. For example '&amp;' becomes '&'. This is adapted from BeautifulSoup, which should be able to do the same thing when called like this --- but this fails t...
def tps(text, min_token_len=2, quant_rate=0.01): ''' :param text: tag-free UTF-8 string of free text :returns string: 32-character md5 hash in hexadecimal Python implementation of the TextProfileSignature provided in SOLR. Unlike most other locality sensitive hashes, a TPS can be indexed as a ...
def make_cleansed_file(i_chunk, tmp_cleansed_path): '''make a temp file of cleansed text''' tmp_cleansed = open(tmp_cleansed_path, 'wb') for idx, si in enumerate(i_chunk): tmp_cleansed.write('<FILENAME docid="%s">\n' % si.stream_id) tmp_cleansed.write(si.body.cleansed) ## how to deal...
def make_ner_file(tagger_id, tmp_cleansed_path, tmp_ner_path, pipeline_root): '''run child process to get OWPL output''' params = dict(INPUT_FILE=tmp_cleansed_path, #RAW_OUTPUT_FILE=tmp_ner_raw_path, OUTPUT_FILE=tmp_ner_path, PIPELINE_ROOT=pipeline_root) ...
def cleanse(span): '''Convert a string of text into a lowercase string with no punctuation and only spaces for whitespace. :param span: string ''' try: ## attempt to force it to utf8, which might fail span = span.encode('utf8', 'ignore') except: pass ## lowercase, st...
def align_chunk_with_ner(tmp_ner_path, i_chunk, tmp_done_path): ''' iterate through the i_chunk and tmp_ner_path to generate a new Chunk with body.ner ''' o_chunk = Chunk() input_iter = i_chunk.__iter__() ner = '' stream_id = None all_ner = xml.dom.minidom.parse(open(tmp_ner_path)) ...
def make_absolute_paths(config): '''given a config dict with streamcorpus_pipeline as a key, find all keys under streamcorpus_pipeline that end with "_path" and if the value of that key is a relative path, convert it to an absolute path using the value provided by root_path ''' if not 'streamcor...
def make_hash(obj): ''' Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). See second answer (not the accepted answer): http://stackoverflow.com/questions/5884066/hashing-a-python-dictio...
def instantiate_config(config): '''setup the config and load external modules This updates 'config' as follows: * All paths are replaced with absolute paths * A hash and JSON dump of the config are stored in the config * If 'pythonpath' is in the config, it is added to sys.path * If 'setup_mod...
def generate_john_smith_chunk(path_to_original): ''' This _looks_ like a Chunk only in that it generates StreamItem instances when iterated upon. ''' ## Every StreamItem has a stream_time property. It usually comes ## from the document creation time. Here, we assume the JS corpus ## was cr...
def re_based_make_clean_visible(html): ''' Takes an HTML-like binary string as input and returns a binary string of the same length with all tags replaced by whitespace. This also detects script and style tags, and replaces the text between them with whitespace. Pre-existing whitespace of any k...
def make_clean_visible(_html, tag_replacement_char=' '): ''' Takes an HTML-like Unicode string as input and returns a UTF-8 encoded string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. This does not detec...
def non_tag_chars_from_raw(html): '''generator that yields clean visible as it transitions through states in the raw `html` ''' n = 0 while n < len(html): # find start of tag angle = html.find('<', n) if angle == -1: yield html[n:] n = len(html) ...
def make_clean_visible_from_raw(_html, tag_replacement_char=' '): '''Takes an HTML-like Unicode (or UTF-8 encoded) string as input and returns a Unicode string with all tags replaced by whitespace. In particular, all Unicode characters inside HTML are replaced with a single whitespace character. Th...
def make_clean_visible_file(i_chunk, clean_visible_path): '''make a temp file of clean_visible text''' _clean = open(clean_visible_path, 'wb') _clean.write('<?xml version="1.0" encoding="UTF-8"?>') _clean.write('<root>') for idx, si in enumerate(i_chunk): if si.stream_id is None: ...
def cleanse(span, lower=True): '''Convert a unicode string into a lowercase string with no punctuation and only spaces for whitespace. Replace PennTreebank escaped brackets with ' ': -LRB- -RRB- -RSB- -RSB- -LCB- -RCB- (The acronyms stand for (Left|Right) (Round|Square|Curly) Bracket.) http://www.cis.upenn.edu/~tr...