
Homoglyphs: get similar letters, convert to ASCII, detect possible languages and UTF-8 group.
分支: https://github.com/orsinium/forks
Homoglyphs —— 用于获取同形字并转换为 ASCII 的 Python 库。
它是 confusable_homoglyphs 的更智能版本:
sudo pip install homoglyphs
解释某事物的最佳方式是展示其工作原理。那么,让我们看一下实际用法。
导入:
import homoglyphs as hg
# 检测
hg.Languages.detect('w')
# {'pl', 'da', 'nl', 'fi', 'cz', 'sr', 'pt', 'it', 'en', 'es', 'sk', 'de', 'fr', 'ro'}
hg.Languages.detect('т')
# {'mk', 'ru', 'be', 'bg', 'sr'}
hg.Languages.detect('.')
# set()
# 获取语言的字母表
hg.Languages.get_alphabet(['ru'])
# {'в', 'Ё', 'К', 'Т', ..., 'Р', 'З', 'Э'}
# 获取所有语言
hg.Languages.get_all()
# {'nl', 'lt', ..., 'de', 'mk'}
类别 —— (来自 ISO 15924 的别名)。
# 检测
hg.Categories.detect('w')
# 'LATIN'
hg.Categories.detect('т')
# 'CYRILLIC'
hg.Categories.detect('.')
# 'COMMON'
# 获取类别的字母表
hg.Categories.get_alphabet(['CYRILLIC'])
# {'ӗ', 'Ԍ', 'Ґ', 'Я', ..., 'Э', 'ԕ', 'ӻ'}
# 获取所有类别
hg.Categories.get_all()
# {'RUNIC', 'DESERET', ..., 'SOGDIAN', 'TAI_LE'}
获取同形字:
# 获取同形字(默认初始化拉丁字母表)
hg.Homoglyphs().get_combinations('q')
# ['q', '𝐪', '𝑞', '𝒒', '𝓆', '𝓺', '𝔮', '𝕢', '𝖖', '𝗊', '𝗾', '𝘲', '𝙦', '𝚚']
字母表加载:
# 通过类别在初始化时加载字母表
homoglyphs = hg.Homoglyphs(categories=('LATIN', 'COMMON', 'CYRILLIC')) # 在此处加载字母表
homoglyphs.get_combinations('гы')
# ['rы', 'гы', 'ꭇы', 'ꭈы', '𝐫ы', '𝑟ы', '𝒓ы', '𝓇ы', '𝓻ы', '𝔯ы', '𝕣ы', '𝖗ы', '𝗋ы', '𝗿ы', '𝘳ы', '𝙧ы', '𝚛ы']
# 通过语言在初始化时加载字母表
homoglyphs = hg.Homoglyphs(languages={'ru', 'en'}) # 在此处加载字母表
homoglyphs.get_combinations('гы')
# ['rы', 'гы']
# 手动在初始化时设置字母表 # eng rus
homoglyphs = hg.Homoglyphs(alphabet='abc абс')
homoglyphs.get_combinations('с')
# ['c', 'с']
# 按需加载字母表
homoglyphs = hg.Homoglyphs(languages={'en'}, strategy=hg.STRATEGY_LOAD)
# ^ 此处将为 "en" 语言加载字母表
homoglyphs.get_combinations('гы')
# ^ 此处将为 "ru" 语言加载字母表
# ['rы', 'гы']
你可以根据需要组合 categories、languages、alphabet 以及任何策略。策略指定如何处理尚未加载的字符:
STRATEGY_LOAD:为该字符加载类别STRATEGY_IGNORE:将字符添加到结果中STRATEGY_REMOVE:从结果中移除该字符homoglyphs = hg.Homoglyphs(languages={'en'}, strategy=hg.STRATEGY_LOAD)
# 转换
homoglyphs.to_ascii('ТЕСТ')
# ['TECT']
homoglyphs.to_ascii('ХР123.') # 这是西里尔字母 "х" 和 "р"
# ['XP123.', 'XPI23.', 'XPl23.']
# 默认情况下,包含无法转换字符的字符串将被忽略
homoglyphs.to_ascii('лол')
# []
# 你可以设置策略,从结果中移除未转换的非 ASCII 字符
homoglyphs = hg.Homoglyphs(
languages={'en'},
strategy=hg.STRATEGY_LOAD,
ascii_strategy=hg.STRATEGY_REMOVE,
)
homoglyphs.to_ascii('лол')
# ['o']
# 你还可以设置允许的 ASCII 字符代码范围(默认 0-128):
homoglyphs = hg.Homoglyphs(
languages={'en'},
strategy=hg.STRATEGY_LOAD,
ascii_strategy=hg.STRATEGY_REMOVE,
ascii_range=range(ord('a'), ord('z')),
)
homoglyphs.to_ascii('ХР123.')
# ['l']
homoglyphs.to_ascii('хр123.')
# ['xpl']