Suppose I have a bunch of files in UTF-8 that I send to an external API in unicode. The API operates on each unicode string and returns a list with (character_offset, substr)
tuples.
The output I need is the begin and end byte offset for each found substring. If I'm lucky the input text contains only ASCII characters (making character offset and byte offset identical), but this is not always the case. How can I find the begin and end byte offsets for a known begin character offset and substring?
I've answered this question myself, but look forward to other solutions to this problem that are more robust, more efficient, and/or more readable.
To convert character offsets to byte offsets when needed, I
encode('utf8')
the text leading up to the found substring if there are any non-ASCII characters in the input text, and take its length as begin offset.This implementation works, but it encodes a (large) part of the text for each found substring.
I'd solve this using a dictionary mapping character offsets to byte offsets and then looking up the offsets in that.
Performance of this solution as compared to yours depends a lot on the size of the input and the amount of substrings involved. Local micro-benchmarking suggests that encoding each individual character in a text takes about 1000 times as long as encoding the entire text at once.