MCPcopy Create free account
hub / github.com/aboutcode-org/scancode-toolkit / as_unicode

Function as_unicode

src/textcode/analysis.py:250–284  ·  view source on GitHub ↗

Return a unicode text line from a text line. Try to decode line as Unicode. Try first some default encodings, then attempt Unicode trans-literation and finally fall-back to ASCII strings extraction. TODO: Add file/magic detection, unicodedmanit/BS3/4

(line)

Source from the content-addressed store, hash-verified

248
249
250def as_unicode(line):
251 """
252 Return a unicode text line from a text line.
253 Try to decode line as Unicode. Try first some default encodings,
254 then attempt Unicode trans-literation and finally
255 fall-back to ASCII strings extraction.
256
257 TODO: Add file/magic detection, unicodedmanit/BS3/4
258 """
259 if isinstance(line, str):
260 return remove_null_bytes(line)
261
262 try:
263 s = line.decode('UTF-8')
264 except UnicodeDecodeError:
265 try:
266 # FIXME: latin-1 may never fail
267 s = line.decode('LATIN-1')
268 except UnicodeDecodeError:
269 try:
270 # Convert some byte string to ASCII characters as Unicode including
271 # replacing accented characters with their non- accented NFKD
272 # equivalent. Non ISO-Latin and non ASCII characters are stripped
273 # from the output. Does not preserve the original length offsets.
274 # For Unicode NFKD equivalence, see:
275 # http://en.wikipedia.org/wiki/Unicode_equivalence
276 s = unicodedata.normalize('NFKD', line).encode('ASCII')
277 except UnicodeDecodeError:
278 try:
279 enc = chardet.detect(line)['encoding']
280 s = str(line, enc)
281 except UnicodeDecodeError:
282 # fall-back to strings extraction if all else fails
283 s = strings.string_from_string(s)
284 return remove_null_bytes(s)
285
286
287def remove_null_bytes(s):

Calls 5

remove_null_bytesFunction · 0.85
decodeMethod · 0.45
encodeMethod · 0.45
normalizeMethod · 0.45
detectMethod · 0.45