我正在处理多语言文本数据,其中包括使用西里尔字母的俄语和土耳其语。我基本上必须比较两个文件中的单词my_file
and check_file
如果这些词在my_file
可以找到check_file
,将它们写入输出文件中,保留两个输入文件中有关这些单词的元信息。
有些单词是小写的,而其他单词是大写的,所以我必须将所有单词都小写才能比较它们。当我使用 Python 3.6.5 且 Python 3 默认使用 unicode 时,它会处理小写字母,然后正确处理西里尔字母的大写字母。然而,对于土耳其语,某些字母处理不正确。大写'İ'
应该对应小写'i'
, 大写'I'
应该对应小写'ı'
和小写'i'
应该对应于大写'İ'
如果我在控制台中键入以下内容,则情况并非如此:
>>> print('İ'.lower())
i̇ # somewhat not rendered correctly, corresponds to unicode 'i\u0307'
>>> print('I'.lower())
i
>>> print('i'.upper())
I
我正在做如下(简化的示例代码):
# python my_file check_file language
import sys
language = sys.argv[3]
# code to get the files as lists
my_file_list = [['ıspanak', 'N'], ['ısır', 'N'], ['acık', 'V']]
check_file_list = [['109', 'Ispanak', 'food_drink'], ['470', 'Isır', 'action_words'], [409, 'Acık', 'action_words']]
# get the lists as dict
my_dict = {}
check_dict = {}
for l in my_file_list:
word = l[0].lower()
pos = l[1]
my_dict[word] = pos
for l in check_file_list:
word_id = l[0]
word = l[1].lower()
word_cat = l[2]
check_dict[word] = [word_id, word_cat]
# compare the two dicts
for word, pos in my_dict.items():
if word in check_dict:
word_id = check_dict[word][0]
word_cat = check_dict[word][1]
print(word, pos, word_id, word_cat)
这只给了我一个结果,但它应该给我三个单词作为结果:
acık V 409 action_words
到目前为止我所做的基于:
- 阅读建议使用的已接受答案PyICU https://pypi.org/project/PyICU/但我希望我的代码可以使用,而无需人们安装东西,所以我没有实现它。
- 试着
import locale
and locale.setlocale(locale.LC_ALL, 'tr_TR.UTF-8')
正如问题中提到的,但它没有改变任何东西。
-
实现两个功能turkish_lower(self)
and turkish_upper(self)
对于第二个答案中描述的三个有问题的字母,这似乎是唯一的解决方案:
def turkish_lower(self):
self = re.sub(r'İ', 'i', self)
self = re.sub(r'I', 'ı', self)
self = self.lower()
return self
def turkish_upper(self):
self = re.sub(r'i', 'İ', self)
self = self.upper()
return self
但是我怎样才能使用这两个函数而不需要检查if language == 'Turkish'
每次?我应该重写内置函数吗lower()
and upper()
?如果是的话,Pythonic 的做法是什么?我是否应该为我正在使用的各种语言实现类并覆盖土耳其语类中的内置函数?