功能Unicod

2024-04-25 23:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个程序,其中有一个函数叫做stt.stt()我是西班牙人,所以我得去掉波浪形文字,把文字翻过来stt.stt()转换为unicode,为此我有以下函数:

def remove_tildes(s):
   return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) #Remove spanish tildes so there won't be errors with ascii
phrase=remove_tildes(stt.stt())

但是当我运行程序时,我得到了一个错误:

File "./program2.py", line 14, in remove_tildes
    return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) #Remove spanish tildes so there won't be errors with ascii
TypeError: must be unicode, not None

为了解决这个问题,我尝试了phrase=remove_tildes(basestring(stt.stt(), unicode))phrase=remove_tildes(u stt.stt())phrase=remove_tildes(unicode stt.stt()) 但是什么都不管用,我也读过这个https://docs.python.org/2/library/unicodedata.html但是我仍然不知道该怎么做来修复这个问题 有人能帮我吗?你知道吗


Tags: 函数in程序forreturnunicodeberemove
2条回答

是否有可能传递None作为参数?你知道吗

尝试:

def remove_tildes(s):
   if s:
       return ''.join((c for c in unicodedata.normalize('NFD', s) 
                       if unicodedata.category(c) != 'Mn'))

sNone

>>> import unicodedata
>>> unicodedata.normalize('NFD', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be unicode, not None

检查stt.stt()返回的内容,或者处理None情况。你知道吗

生成器表达式括号是可选的,但是当使用str.join()时,在这里使用列表理解实际上更快(代码将输入转换为列表,因为它需要遍历列表两次):

def remove_tildes(s):
   # Remove spanish tildes so there won't be errors with ascii
   return ''.join([
       c for c in unicodedata.normalize('NFD', s or u'')
       if unicodedata.category(c) != 'Mn'])

其中s or u''通过将s替换为空字符串来处理None的情况。你知道吗

相关问题 更多 >