python - 如何将线性字符串变成特里?
问题描述
我正在使用make me a hanzi开源汉字数据集。作为该数据集的一部分,有一些字符串可以将汉字分解成单独的单元(称为部首)。我想将描述字符分解的字符串转换为尝试(以便我可以networkx
用来呈现分解)。
例如对于这个数据库条目:
{"character":"⺳","definition":"net, network","pinyin":[],"decomposition":"⿱冖八","radical":"⺳","matches":[[0],[0],[1],[1]]}
这个字符的分解是。
- Node(1, char='⿱')
- Node(2, char='冖') # an edge connects '⿱' to '冖'
- Node(3, char='八') # an edge connects '⿱' to '八'
到目前为止,我已经想出了一个脚本来将字符串分解转换为字典(但不是图表)。
decomposition_types = {
'top-bottom': '⿱',
'left-right': '⿰',
'diagonal-corners': '⿻',
'over-under': '⿺',
'under-over': '⿹',
'over-under-reversed': '⿸',
'top-bottom-middle': '⿳',
'left-right-middle': '⿲',
'inside-outside': '⿴',
'outside-inside': '⿵',
'outside-inside2': '⿷',
'inside-outside2': '⿶'
# 'unknown': '?'
}
decomposition_types_reversed = dict(((value, key) for key, value in decomposition_types.items()))
file = []
if not os.path.isfile('data/dictionary.json'):
with open('data/dictionary.txt') as d:
for line in d:
file.append(json.loads(line))
for i, item in enumerate(file):
item['id'] = i + 1
json.dump(file, open('data/dictionary.json', 'w+'))
else:
file = json.load(open('data/dictionary.json'))
def is_parsed(blocks):
for block in blocks:
if not block['is_unit']:
return False
return True
def search(character, dictionary=file):
for hanzi in dictionary:
if hanzi['character'] == character:
return hanzi
return False
def parse(decomp):
if len(decomp) == 1:
return {"spacing": '?'}
blocks = []
n_loops = 0
for item in decomp:
blocks.append({"char": item, "is_spacing": item in decomposition_types_reversed, "is_unit": False})
while not is_parsed(blocks):
for i, item in enumerate(blocks):
if "is_spacing" in item:
if item['is_spacing']:
next_items = decomposition_types_reversed[item['char']].count('-') + 1
can_match = True
for x in blocks[i + 1:i + 1 + next_items]:
try:
if x['char'] in decomposition_types_reversed:
can_match = False
except KeyError:
pass
if can_match:
blocks[i] = {"spacing": item['char'],
"chars": [l['char'] if 'char' in l else l for l in
blocks[i + 1:i + 1 + next_items]],
"is_unit": True}
del blocks[i + 1:i + 1 + next_items]
n_loops += 1
if n_loops > 10:
print(decomp)
sys.exit()
return blocks
解决方案
推荐阅读
- c# - AutoMapper 10 ValueTransformer 未针对值类型目标执行
- azure-media-services - Azure 媒体服务:client.Assets.CreatOrUpdateAsync 导致错误:资源类型无效
- php - CORS:标头存在,但“if”语句否定标头
- lucene - 如何在 Lucene.Net 4.8 中使用 HIGH_COMPRESSION
- python - 有没有一种最佳方法来获取分组熊猫数据框中的所有值组合?
- sql - 如何检查一条记录在不同表中重复了多少次
- macos - mac 上的 Veracrypt 容器 - 如何设置权限(与 .ssh 文件兼容)
- javascript - html div 的起始位置和随机移动
- javascript - 在以角度形式显示之前检查记录是否存在
- javascript - 我在使用 npx-create-reat-app 创建我的 React 应用程序时遇到问题