text stringlengths 81 112k |
|---|
Given an onset for a match, iterate over all completions of that match
This iterator works recursively. At each level the match is extended
with a new set of relations based on vertices in the pattern graph
that are at a distances 'level' from the starting vertex
def _iter_matches(sel... |
Writes a single molecule to a pdb file.
This function is based on the pdb file specification:
http://www.wwpdb.org/documentation/format32/sect9.html
For convenience, the relevant table is copied and the character indexes are
transformed to C-style (starting from zero)
======= ... |
Loads a single molecule from a pdb file.
This function does support only a small fragment from the pdb specification.
It assumes that there is only one molecular geometry in the pdb file.
def load_pdb(filename):
"""Loads a single molecule from a pdb file.
This function does support only a sm... |
Converts a ZMatrix back to cartesian coordinates.
def zmat_to_cart(zmat):
"""Converts a ZMatrix back to cartesian coordinates."""
numbers = zmat["number"]
N = len(numbers)
coordinates = np.zeros((N, 3), float)
# special cases for the first coordinates
coordinates[1, 2] = zmat["distance"][1]
... |
Get a new reference atom for a row in the ZMatrix
The reference atoms should obey the following conditions:
- They must be different
- They must be neighbours in the bond graph
- They must have an index lower than the current atom
If multiple candidate refs... |
Convert cartesian coordinates to ZMatrix format
Argument:
coordinates -- Cartesian coordinates (numpy array Nx3)
The coordinates must match with the graph that was used to initialize
the ZMatrixGenerator object.
def cart_to_zmat(self, coordinates):
"""Convert c... |
Return ``True`` if the mapper can map all the IPA characters
in the given IPA string.
:param IPAString ipa_string: the IPAString to be parsed
:rtype: bool
def can_map_ipa_string(self, ipa_string):
"""
Return ``True`` if the mapper can map all the IPA characters
in the g... |
Convert the given IPAString to a string
containing the corresponding ASCII IPA representation.
:param IPAString ipa_string: the IPAString to be parsed
:param bool ignore: if ``True``, ignore Unicode characters that are not IPA valid
:param bool return_as_list: if ``True``, return as a l... |
Convert the given Unicode string, representing an IPA string,
to a string containing the corresponding mapped representation.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool ignore: if ``True``, ignore Unicode ch... |
Print Unicode characterss that are not IPA valid,
if requested by the user.
:param list invalid_chars: a list (possibly empty) of invalid Unicode characters
:param dict vargs: the command line parameters
def print_invalid_chars(invalid_chars, vargs):
"""
Print Unicode characterss that are not IPA ... |
Print the canonical representation of the given string.
It will replace non-canonical compound characters
with their canonical synonym.
:param str string: the string to act upon
:param dict vargs: the command line arguments
def command_canonize(string, vargs):
"""
Print the canonical represe... |
Print a list of all IPA characters in the given string.
It will print the Unicode representation, the full IPA name,
and the Unicode "U+"-prefixed hexadecimal codepoint representation
of each IPA character.
:param str string: the string to act upon
:param dict vargs: the command line arguments
de... |
Check if the given string is IPA valid.
If the given string is not IPA valid,
print the invalid characters.
:param str string: the string to act upon
:param dict vargs: the command line arguments
def command_check(string, vargs):
"""
Check if the given string is IPA valid.
If the given s... |
Remove characters that are not IPA valid from the given string,
and print the remaining string.
:param str string: the string to act upon
:param dict vargs: the command line arguments
def command_clean(string, vargs):
"""
Remove characters that are not IPA valid from the given string,
and prin... |
Print the ARPABEY ASCII string corresponding to the given Unicode IPA string.
:param str string: the string to act upon
:param dict vargs: the command line arguments
def command_u2a(string, vargs):
"""
Print the ARPABEY ASCII string corresponding to the given Unicode IPA string.
:param str stri... |
Print the Kirshenbaum ASCII string corresponding to the given Unicode IPA string.
:param str string: the string to act upon
:param dict vargs: the command line arguments
def command_u2k(string, vargs):
"""
Print the Kirshenbaum ASCII string corresponding to the given Unicode IPA string.
:param ... |
Entry point.
def main():
"""
Entry point.
"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
for arg in ARGUMENTS:
if "action" in arg:
if arg["short"] is not None:
parser.add_argument(arg["short"], arg["long"], action=arg["action"], help=arg["help"])
... |
Set the list of IPAChar objects composing the IPA string
:param list value: list of IPAChar objects
def ipa_chars(self, value):
"""
Set the list of IPAChar objects composing the IPA string
:param list value: list of IPAChar objects
"""
if value is None:
sel... |
Return ``True`` if the IPA string is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string,
2. a list of IPAChar objects, and
3. another IPAString.
:param variant other: the object to be compared against
:param bool ignore: if other is a ... |
Return a new IPAString, containing the canonical representation of the current string,
that is, the one composed by the (prefix) minimum number of IPAChar objects.
:rtype: IPAString
def canonical_representation(self):
"""
Return a new IPAString, containing the canonical representation ... |
Return a new IPAString, containing only the IPA characters specified
by the ``chars`` string.
Valid values for ``chars`` are:
* ``consonants`` or ``cns``
* ``vowels`` or ``vwl``
* ``letters`` or ``cns_vwl``
* ``cns_vwl_pstr`` or ``cvp``
* ``cns_vwl_pstr_long`` o... |
Return a new IPAString, containing only the consonants in the current string.
:rtype: IPAString
def consonants(self):
"""
Return a new IPAString, containing only the consonants in the current string.
:rtype: IPAString
"""
return IPAString(ipa_chars=[c for c in self.ipa... |
Return a new IPAString, containing only the vowels in the current string.
:rtype: IPAString
def vowels(self):
"""
Return a new IPAString, containing only the vowels in the current string.
:rtype: IPAString
"""
return IPAString(ipa_chars=[c for c in self.ipa_chars if c.... |
Return a new IPAString, containing only:
1. the consonants, and
2. the vowels
in the current string.
:rtype: IPAString
def cns_vwl(self):
"""
Return a new IPAString, containing only:
1. the consonants, and
2. the vowels
in the... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the primary stress diacritics
in the current string.
:rtype: IPAString
def cns_vwl_pstr(self):
"""
Return a new IPAString, containing only:
1. the conson... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the stress diacritics
in the current string.
:rtype: IPAString
def cns_vwl_str(self):
"""
Return a new IPAString, containing only:
1. the consonants,
... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the stress diacritics, and
4. the length diacritics
in the current string.
:rtype: IPAString
def cns_vwl_str_len(self):
"""
Return a new IPAString, containing onl... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the primary stress diacritics, and
4. the long suprasegmental
in the current string.
:rtype: IPAString
def cns_vwl_pstr_long(self):
"""
Return a new IPAString, co... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the stress diacritics,
4. the length diacritics, and
5. the word breaks
in the current string.
:rtype: IPAString
def cns_vwl_str_len_wb(self):
"""
Return ... |
Return a new IPAString, containing only:
1. the consonants,
2. the vowels, and
3. the stress diacritics,
4. the length diacritics,
5. the word breaks, and
6. the syllable breaks
in the current string.
:rtype: IPAString
def cns_vwl_str_len_wb_sb... |
Convert a Unicode field into the corresponding list of Unicode strings.
The (input) Unicode field is a Unicode string containing
one or more Unicode codepoints (``xxxx`` or ``U+xxxx`` or ``xxxx_yyyy``),
separated by a space.
:param str string: the (input) Unicode field
:rtype: list of Unicode stri... |
Convert an ASCII field into the corresponding list of Unicode strings.
The (input) ASCII field is a Unicode string containing
one or more ASCII codepoints (``00xx`` or ``U+00xx`` or
an ASCII string not starting with ``00`` or ``U+``),
separated by a space.
:param str string: the (input) ASCII fiel... |
Convert a tuple of raw values, according to the given line format.
:param tuple value_tuple: the tuple of raw values
:param str format_string: the format of the tuple
:rtype: list of tuples
def convert_raw_tuple(value_tuple, format_string):
"""
Convert a tuple of raw values, according to the given... |
Load a data file, with one record per line and
fields separated by ``field_separator``,
returning a list of tuples.
It ignores lines starting with ``comment_string`` or empty lines.
If ``values_per_line`` is not ``None``,
check that each line (tuple)
has the prescribed number of values.
:... |
Load the IPA data from the built-in IPA database, creating the following globals:
1. ``IPA_CHARS``: list of all IPAChar objects
2. ``UNICODE_TO_IPA``: dict mapping a Unicode string (often, a single char) to an IPAChar
3. ``UNICODE_TO_IPA_MAX_KEY_LENGTH``: length of a longest key in ``UNICODE_TO_IPA``
4... |
Return a list of (non-empty) substrings of the given string,
where each substring is either:
1. the longest string starting at the current index
that is a key in the dictionary, or
2. a single character that is not a key in the dictionary.
If ``single_char_parsing`` is ``False``,
parse ... |
Return a list of (non-empty) substrings of the given string,
where each substring is either:
1. the longest Unicode string starting at the current index
representing a (known) valid IPA character, or
2. a single Unicode character (which is not IPA valid).
If ``single_char_parsing`` is ``Fal... |
Return the list of Unicode characters
in the given Unicode string
that are not IPA valid.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param bool indices: if ``True``, return a list of pairs (index, invalid character),
... |
Remove all Unicode characters that are not IPA valid
from the given string,
and return a list of substrings of the given string,
each mapping to a (known) valid IPA character.
Return ``None`` if ``unicode_string`` is ``None``.
:param str unicode_string: the Unicode string to be parsed
:param b... |
Return a list containing the descriptors in the given object.
The ``obj`` can be a list or a set of descriptor strings, or a Unicode string.
If ``obj`` is a Unicode string, it will be split using spaces as delimiters.
:param variant obj: the object to be parsed
:rtype: list
:raise TypeError:... |
Return a list containing the canonical string for the given object.
The ``obj`` can be a list or a set of descriptor strings, or a Unicode string.
If ``obj`` is a Unicode string, it will be split using spaces as delimiters.
:param variant obj: the object to be parsed
:rtype: str
:raise TypeE... |
Return ``True`` if the given object is a list of IPAChar objects.
:param object obj: the object to test
:rtype: bool
def is_list_of_ipachars(obj):
"""
Return ``True`` if the given object is a list of IPAChar objects.
:param object obj: the object to test
:rtype: bool
"""
if isinstance... |
Return ``True`` if the IPA character is equivalent to the ``other`` object.
The ``other`` object can be:
1. a Unicode string, containing the representation of the IPA character,
2. a Unicode string, containing a space-separated list of descriptors,
3. a list of Unicode strings, contain... |
Return the canonical value of a descriptor of the character,
provided it is present in the given descriptor group.
If not present, return ``None``.
:param IPADescriptorGroup descriptor_group: the descriptor group to be checked against
:rtype: str
def dg_value(self, descriptor_group):
... |
Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: the descriptor to be checked against
:rtype: bool
def has_descriptor(self, descriptor):
"""
Return ``True`` if the character has the given descriptor.
:param IPADescriptor descriptor: t... |
Set the voicing of the consonant.
:param str value: the value to be set
def voicing(self, value):
"""
Set the voicing of the consonant.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_C_VOICING):
raise ValueError("Unrec... |
Set the place of articulation of the consonant.
:param str value: the value to be set
def place(self, value):
"""
Set the place of articulation of the consonant.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_C_PLACE):
... |
Set the manner of articulation of the consonant.
:param str value: the value to be set
def manner(self, value):
"""
Set the manner of articulation of the consonant.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_C_MANNER):
... |
Set the height of the vowel.
:param str value: the value to be set
def height(self, value):
"""
Set the height of the vowel.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_V_HEIGHT):
raise ValueError("Unrecognized valu... |
Set the backness of the vowel.
:param str value: the value to be set
def backness(self, value):
"""
Set the backness of the vowel.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_V_BACKNESS):
raise ValueError("Unrecogni... |
Set the roundness of the vowel.
:param str value: the value to be set
def roundness(self, value):
"""
Set the roundness of the vowel.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_V_ROUNDNESS):
raise ValueError("Unrec... |
Load the Kirshenbaum ASCII IPA data from the built-in database.
def _load_data(self):
"""
Load the Kirshenbaum ASCII IPA data from the built-in database.
"""
ipa_canonical_string_to_ascii_str = dict()
for line in load_data_file(
file_path=self.DATA_FILE_PATH,
... |
Return the canonical value corresponding to the given query value.
Return ``None`` if the query value is not present in any descriptor of the group.
:param str query: the descriptor value to be checked against
def canonical_value(self, query):
"""
Return the canonical value correspond... |
Load the ARPABET ASCII IPA data from the built-in database.
def _load_data(self):
"""
Load the ARPABET ASCII IPA data from the built-in database.
"""
ipa_canonical_string_to_ascii_str = dict()
for line in load_data_file(
file_path=self.DATA_FILE_PATH,
fil... |
Return ``True`` if the given string is a Unicode string,
that is, of type ``unicode`` in Python 2 or ``str`` in Python 3.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to be checked
:rtype: bool
def is_unicode_string(string):
"""
Return ``True`` if the given string ... |
Return a Unicode string out of the given string.
On Python 2, it calls ``unicode`` with ``utf-8`` encoding.
On Python 3, it just returns the given string.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to convert to Unicode
:rtype: (Unicode) str
def to_unicode_strin... |
Return the given string (either byte string or Unicode string)
converted to native-str, that is,
a byte string on Python 2, or a Unicode string on Python 3.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to convert to native-str
:rtype: native-str
def to_str(string):
... |
Return the Unicode character with the given codepoint,
given as an hexadecimal string.
Return ``None`` if ``hex_string`` is ``None`` or is empty.
Example::
"0061" => a
"U+0061" => a
:param str hex_string: the Unicode codepoint of the desired character
:rtype: (Unicode) str
def ... |
Return a string containing the Unicode hexadecimal codepoint
of each Unicode character in the given Unicode string.
Return ``None`` if ``unicode_string`` is ``None``.
Example::
a => U+0061
ab => U+0061 U+0062
:param str unicode_string: the Unicode string to convert
:rtype: (Unico... |
Create an lxml.html.HtmlElement from a string with html.
XXX: mostly copy-pasted from parsel.selector.create_root_node
def parse_html(html):
""" Create an lxml.html.HtmlElement from a string with html.
XXX: mostly copy-pasted from parsel.selector.create_root_node
"""
body = html.strip().replace('\x... |
Convert a html tree to text. Tree should be cleaned with
``html_text.html_text.cleaner.clean_html`` before passing to this
function.
See html_text.extract_text docstring for description of the
approach and options.
def etree_to_text(tree,
guess_punct_space=True,
gue... |
Convert a cleaned parsel.Selector to text.
See html_text.extract_text docstring for description of the approach
and options.
def selector_to_text(sel, guess_punct_space=True, guess_layout=True):
""" Convert a cleaned parsel.Selector to text.
See html_text.extract_text docstring for description of the a... |
Clean parsel.selector.
def cleaned_selector(html):
""" Clean parsel.selector.
"""
import parsel
try:
tree = _cleaned_html_tree(html)
sel = parsel.Selector(root=tree, type='html')
except (lxml.etree.XMLSyntaxError,
lxml.etree.ParseError,
lxml.etree.ParserError... |
Convert html to text, cleaning invisible content such as styles.
Almost the same as normalize-space xpath, but this also
adds spaces between inline elements (like <span>) which are
often used as block elements in html markup, and adds appropriate
newlines to make output better formatted.
html shou... |
Gets the JSON file from ArcGIS
def get_json(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'):
"""
Gets the JSON file from ArcGIS
"""
params = {
'where': where,
'outFields': ", ".join(fields),
'returnGeometry': True,
... |
Returns the standard JSON descriptor for the layer. There is a lot of
usefule information in there.
def get_descriptor_for_layer(self, layer):
"""
Returns the standard JSON descriptor for the layer. There is a lot of
usefule information in there.
"""
if not layer in self... |
Pulls out all of the field names for a layer.
def enumerate_layer_fields(self, layer):
"""
Pulls out all of the field names for a layer.
"""
descriptor = self.get_descriptor_for_layer(layer)
return [field['name'] for field in descriptor['fields']] |
Gets a layer and returns it as honest to God GeoJSON.
WHERE 1 = 1 causes us to get everything. We use OBJECTID in the WHERE clause
to paginate, so don't use OBJECTID in your WHERE clause unless you're going to
query under 1000 objects.
def get(self, layer, where="1 = 1", fields=[], count_only=... |
Returns JSON for a Table type. You shouldn't use this directly -- it's
an automatic falback from .get if there is no geometry
def getTable(self, layer, where="1 = 1", fields=[], jsobj=None):
"""
Returns JSON for a Table type. You shouldn't use this directly -- it's
an automatic falback ... |
Get a bunch of layers and concatenate them together into one. This is useful if you
have a map with layers for, say, every year named stuff_2014, stuff_2013, stuff_2012. Etc.
Optionally, you can stuff the source layer name into a field of your choosing.
>>> arc.getMultiple([0, 3, 5], layer_nam... |
Determines the version of a .py, .wdl, or .cwl file.
def get_version(extension, workflow_file):
'''Determines the version of a .py, .wdl, or .cwl file.'''
if extension == 'py' and two_seven_compatible(workflow_file):
return '2.7'
elif extension == 'cwl':
return yaml.load(open(workflow_file)... |
Returns the version of the file and the file extension.
Assumes that the file path is to the file directly ie, ends with a valid file extension.Supports checking local
files as well as files at http:// and https:// locations. Files at these remote locations are recreated locally to
enable our approach to v... |
Changes relative paths in a json/yaml file to be relative
to where the json/yaml file is located.
:param jsonyaml_file: Path to a json/yaml file.
def modify_jsonyaml_paths(jsonyaml_file):
"""
Changes relative paths in a json/yaml file to be relative
to where the json/yaml file is located.
:pa... |
:param str workflow_file: Path to cwl/wdl file. Can be http/https/file.
:param json_path: Path to accompanying json file.
:param attachments: Any other files needing to be uploaded to the server.
:return: A list of tuples formatted to be sent in a post to the wes-server (Swagger API).
def build_wes_reque... |
Get information about Workflow Execution Service. May
include information related (but not limited to) the
workflow descriptor formats, versions supported, the
WES API versions supported, and information about general
the service availability.
:param str auth: String to send in ... |
Composes and sends a post request that signals the wes server to run a workflow.
:param str workflow_file: A local/http/https path to a cwl/wdl/python workflow file.
:param str jsonyaml: A local path to a json or yaml file.
:param list attachments: A list of local paths to files that will be up... |
Cancel a running workflow.
:param run_id: String (typically a uuid) identifying the run.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes server listens at (d... |
Get detailed info about a running workflow.
:param run_id: String (typically a uuid) identifying the run.
:param str auth: String to send in the auth header.
:param proto: Schema where the server resides (http, https)
:param host: Port where the post request will be sent and the wes ser... |
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input c... |
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
def getstate(self):
"""
Returns RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
"""
state = "RUNNING"
exit_code = -1
exi... |
Writes a cwl, wdl, or python file as appropriate from the request dictionary.
def write_workflow(self, request, opts, cwd, wftype='cwl'):
"""Writes a cwl, wdl, or python file as appropriate from the request dictionary."""
workflow_url = request.get("workflow_url")
# link the cwl and json into... |
Calls a command with Popen.
Writes stdout, stderr, and the command to separate files.
:param cmd: A string or array of strings.
:param tempdir:
:return: The pid of the command.
def call_cmd(self, cmd, cwd):
"""
Calls a command with Popen.
Writes stdout, stderr, ... |
Constructs a command to run a cwl/json from requests and opts,
runs it, and deposits the outputs in outdir.
Runner:
opts.getopt("runner", default="cwl-runner")
CWL (url):
request["workflow_url"] == a url to a cwl file
or
request["workflow_attachment"] == input c... |
Returns QUEUED, -1
INITIALIZING, -1
RUNNING, -1
COMPLETE, 0
or
EXECUTOR_ERROR, 255
def getstate(self):
"""
Returns QUEUED, -1
INITIALIZING, -1
RUNNING,... |
Recursively call op(d) for all list subelements and dictionary 'values' that d may have.
def visit(d, op):
"""Recursively call op(d) for all list subelements and dictionary 'values' that d may have."""
op(d)
if isinstance(d, list):
for i in d:
visit(i, op)
elif isinstance(d, dict):
... |
Returns the first option value stored that matches p or default.
def getopt(self, p, default=None):
"""Returns the first option value stored that matches p or default."""
for k, v in self.pairs:
if k == p:
return v
return default |
Returns all option values stored that match p as a list.
def getoptlist(self, p):
"""Returns all option values stored that match p as a list."""
optlist = []
for k, v in self.pairs:
if k == p:
optlist.append(v)
return optlist |
Catch uncaught exceptions and turn them into http errors
def catch_exceptions(orig_func):
"""Catch uncaught exceptions and turn them into http errors"""
@functools.wraps(orig_func)
def catch_exceptions_wrapper(self, *args, **kwargs):
try:
return orig_func(self, *args, **kwargs)
... |
Convert the file name to ASCII and normalize the string.
def _safe_name(file_name, sep):
"""Convert the file name to ASCII and normalize the string."""
file_name = stringify(file_name)
if file_name is None:
return
file_name = ascii_text(file_name)
file_name = category_replace(file_name, UNI... |
Create a secure filename for plain file system storage.
def safe_filename(file_name, sep='_', default=None, extension=None):
"""Create a secure filename for plain file system storage."""
if file_name is None:
return decode_path(default)
file_name = decode_path(file_name)
file_name = os.path.ba... |
Brute-force convert a given object to a string.
This will attempt an increasingly mean set of conversions to make a given
object into a unicode string. It is guaranteed to either return unicode or
None, if all conversions failed (or the value is indeed empty).
def stringify(value, encoding_default='utf-8'... |
Normalize the encoding name, replace ASCII w/ UTF-8.
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return defaul... |
Interpret a chardet result.
def normalize_result(result, default, threshold=0.2):
"""Interpret a chardet result."""
if result is None:
return default
if result.get('confidence') is None:
return default
if result.get('confidence') < threshold:
return default
return normalize_... |
Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text.
def guess_encoding(text, default=DEFAULT_ENCODING):
"""Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding... |
Guess encoding from a file handle.
def guess_file_encoding(fh, default=DEFAULT_ENCODING):
"""Guess encoding from a file handle."""
start = fh.tell()
detector = chardet.UniversalDetector()
while True:
data = fh.read(1024 * 10)
if not data:
detector.close()
break
... |
Wrapper to open that damn file for you, lazy bastard.
def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
"""Wrapper to open that damn file for you, lazy bastard."""
with io.open(file_path, 'rb') as fh:
return guess_file_encoding(fh, default=default) |
Perform unicode compatibility decomposition.
This will replace some non-standard value representations in unicode and
normalise them, while also separating characters and their diacritics into
two separate codepoints.
def decompose_nfkd(text):
"""Perform unicode compatibility decomposition.
This ... |
Perform unicode composition.
def compose_nfc(text):
"""Perform unicode composition."""
if text is None:
return None
if not hasattr(compose_nfc, '_tr'):
compose_nfc._tr = Transliterator.createInstance('Any-NFC')
return compose_nfc._tr.transliterate(text) |
Remove characters from a string based on unicode classes.
This is a method for removing non-text characters (such as punctuation,
whitespace, marks and diacritics) from a piece of text by class, rather
than specifying them individually.
def category_replace(text, replacements=UNICODE_CATEGORIES):
"""R... |
Remove unsafe unicode characters from a piece of text.
def remove_unsafe_chars(text):
"""Remove unsafe unicode characters from a piece of text."""
if isinstance(text, six.string_types):
text = UNSAFE_RE.sub('', text)
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.