Below is one example of how you might write such a function. This solution downloads the official Unicode “Scripts.txt” file (from the Unicode Consortium’s website) that lists all the codepoint ranges for each script. Then, for a given codepoint (or one‐character string), it checks which range contains that codepoint and returns the script name (such as "Latin", "Hangul", etc.).
You can use this code as a module in your project:
python
import urllib.request
# Global cache for script ranges data.
_script_ranges = None
def load_script_data():
"""
Loads Unicode script ranges from the official Scripts.txt file.
Each line in this file (ignoring comments and blank lines) has the format:
<codepoint-range> ; <Script> # <comments>
For example:
0041..005A; Latin # L& [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
Returns:
A list of tuples: (start, end, script) where 'start' and 'end' are integers.
"""
url = "https://unicode.org/Public/UNIDATA/Scripts.txt"
try:
response = urllib.request.urlopen(url)
except Exception as e:
raise RuntimeError("Could not download Unicode script data.") from e
raw_data = response.read().decode('utf-8')
script_ranges = []
for line in raw_data.splitlines():
# Remove comments and whitespace.
line = line.split('#')[0].strip()
if not line:
continue
# Split the line into codepoint/range and script name.
parts = line.split(';')
if len(parts) < 2:
continue # Skip malformed lines.
range_str = parts[0].strip()
script = parts[1].strip()
# A range may be a single codepoint or a range.
if '..' in range_str:
start_str, end_str = range_str.split('..')
start = int(start_str, 16)
end = int(end_str, 16)
else:
start = end = int(range_str, 16)
script_ranges.append((start, end, script))
return script_ranges
def get_unicode_script(cp):
"""
Returns the Unicode script for a given codepoint.
Args:
cp: Can be either an integer (the Unicode codepoint) or a one-character string.
Returns:
A string giving the Unicode script (e.g., "Latin", "Hangul", etc.).
Returns "Unknown" if not found.
Raises:
ValueError: If the input is not an integer or a single-character string.
"""
global _script_ranges
# Convert a single-character string to its corresponding codepoint integer.
if isinstance(cp, str):
if len(cp) != 1:
raise ValueError("Input string must be a single character.")
cp = ord(cp)
elif not isinstance(cp, int):
raise ValueError("Input must be a Unicode codepoint integer or a single character.")
# Load the script data on the first call.
if _script_ranges is None:
_script_ranges = load_script_data()
# Look up the script by iterating over the ranges.
for start, end, script in _script_ranges:
if start <= cp <= end:
return script
return "Unknown"
# Example usage:
if __name__ == '__main__':
# Using a Unicode codepoint as an integer
codepoint = 0x0041 # 'A'
print(f"U+0041: {get_unicode_script(codepoint)}") # Expected: Latin
# Using a character directly
character = "한" # Hangul syllable
print(f"{character}: {get_unicode_script(character)}") # Expected: Hangul
How It Works
Downloading and Parsing Data:
The function load_script_data() downloads the Scripts.txt file from Unicode.org and parses it. Each non-comment line defines either a single codepoint or a range of codepoints along with its corresponding script.
Determining the Script:
The function get_unicode_script(cp) accepts either an integer codepoint or a single-character string. It then ensures that the script data is loaded (caching it in the _script_ranges global variable) and iterates over the ranges to find one that contains the codepoint. If found, it returns the script name.
Usage:
In the example usage at the bottom, the code shows how to retrieve the script for the letter A (which is Latin) and a Hangul syllable.
This function should work for most applications, though you may wish to add error checking or caching to suit your needs.