我想做一个简单的Python脚本,将每个阿拉伯字母映射到音素声音符号。我有一个文件,其中有一堆单词,脚本会读取这些单词,以便将它们转换成音素,我的代码中有以下字典:
.txt文件中的内容:
السلام عليكم
السلام عليكم و رحمة الله
السلام عليكم و رحمة الله و بركاته
الحمد لله
كيف حالك
كيف الحال我代码中的字典:
ar_let_phon_maplist = {u'ﺍ':'A:', u'ﺏ':'B', u'ﺕ':'T', u'ﺙ':'TH', u'ﺝ':'J', u'ﺡ':'H', u'ﺥ':'KH', u'ﻩ':'H', u'ﻉ':'(ayn) ’', u'ﻍ':'GH', u'ﻑ':'F', u'ﻕ':'q', u'ﺹ':u'ṣ', u'ﺽ':u'ḍ', u'ﺩ':'D', u'ﺫ':'DH', u'ﻁ':u'ṭ', u'ﻙ':'K', u'ﻡ':'M', u'ﻥ':'N', u'ﻝ':'L', u'ﻱ':'Y', u'ﺱ':'S', u'ﺵ':'SH', u'ﻅ':u'ẓ', u'ﺯ':'Z', u'ﻭ':'W', u'ﺭ':'R'}我有一个嵌套循环,在这里我读取每一行,转换每个字符:
with codecs.open(sys.argv[1], 'r', encoding='utf-8') as file:
lines = file.readlines()
line_counter = 0
for line in lines:
print "Phonetics In Line " + str(line_counter)
print line + " ",
for word in line:
for character in word:
if character == '\n':
print ""
elif character == ' ':
print " "
else:
print ar_let_phon_maplist[character] + " ",
line_counter +=1这就是我所犯的错误:
Phonetics In Line 0
السلام عليكم
Traceback (most recent call last):
File "grapheme2phoneme.py", line 25, in <module>
print ar_let_phon_maplist[character] + " ",
KeyError: u'\u0627'然后使用Linux命令检查文件类型是否为UTF-8:
file words.txt我得到的输出:
words.txt: UTF-8 Unicode text任何解决这个问题的解决方案,为什么它不映射到字典中的Unicode对象,因为我在ar_let_phon_maplist[character]行中用作键的字符也是Unicode?我的密码有什么问题吗?
发布于 2015-12-31 02:10:09
吸引眼球的第一件事是KeyError。所以你的字典根本不知道文件中遇到的一些符号。展望未来,它不知道任何提交的字符,不仅是关于第一个。
我们能做些什么呢?好的,我们可以将unicode表阿拉伯段中的所有符号添加到我们的字典中。简单吗?是。明白了吗?不是的。
如果您想真正了解这种“奇怪”行为的原因,您应该了解更多关于Unicode的知识。简而言之,有许多字母看起来相似,但序号不同。此外,有时也可以以多种形式提交同一封信。所以比较unicode字符是不是一件小事。
因此,如果允许我使用Python,我将按以下方式解决这个任务。首先,我将在ar_let_phon_maplist字典中对键进行规范化:
ar_let_phon_maplist = {unicodedata.normalize('NFKD', k): v
for k, v in ar_let_phon_maplist.items()}然后,我们将遍历文件中的行、行中的单词和单词中的字符,如下所示:
for index, line in enumerate(lines):
print('Phonetics in line {0}, total {1} symbols'.format(index, len(line)))
unknown = [] # Here will be stored symbols that we haven't found in dict
words = line.split()
for word in words:
print(word, ': ', sep='', end='')
for character in word:
c = unicodedata.normalize('NFKD', character).casefold()
try:
print(ar_let_phon_maplist[c], sep='', end='')
except KeyError:
print('_', sep='', end='')
if c not in unknown:
unknown.append(c)
print()
if unknown:
print('Unrecognized symbols: {0}, total {1} symbols'.format(', '.join(unknown),
len(unknown)))脚本将产生类似这样的内容:
Phonetics in line 4, total 9 symbols
كيف: KYF
حالك: HA:LK发布于 2015-12-31 00:42:11
看来你把那个字忘在字典里了。您有ﺍ (u'\ufe8d',阿拉伯字母ALEF隔离表单),它看起来类似,但是没有ا (u'\u0627',阿拉伯字母ALEF)。
https://stackoverflow.com/questions/34538388
复制相似问题