Python编码问题

Leo*_*soa 4 python django twitter encoding utf-8

所以,我已经阅读了很多关于Python编码和内容的内容 - 也许还不够,但我已经在这方面工作了2天但仍然没有 - 但我仍然遇到麻烦.我会努力尽可能清楚.主要的是我正在尝试删除所有重音和字符,例如#,!,%,&...

问题是,我通过此调用在Twitter Search API上进行查询搜索:

query = urllib2.urlopen(settings.SEARCH_URL + '?%s' % params)
Run Code Online (Sandbox Code Playgroud)

然后,我avaliar_pesquisa()根据输入的标签(或术语)调用方法()来评估我得到的结果:

dados = avaliar_pesquisa(simplejson.loads(query.read()), str(tags))
Run Code Online (Sandbox Code Playgroud)

avaliar_pesquisa(),发生以下情况:

def avaliar_pesquisa(dados, tags):
    resultados = []
    # Percorre os resultados
    for i in dados['results']
        resultados.append({'texto'          : i['text'],
                           'imagem'         : i['profile_image_url'],
                           'classificacao'  : avaliar_texto(i['text'], tags),
                           'timestamp'      : i['created_at'],
                         })
Run Code Online (Sandbox Code Playgroud)

请注意,avaliar_texto()它会评估推文文本.以下几行确实存在问题:

def avaliar_texto(texto, tags):
    # Remove accents
    from unicodedata import normalize
    def strip_accents(txt):
        return normalize('NFKD', txt.decode('utf-8'))

    # Split
    texto_split = strip_accents(texto)
    texto_split = texto.lower().split()

    # Remove non-alpha characters
    import re
    pattern = re.compile('[\W_]+')
    texto_aux = []
    for i in texto_split:
        texto_aux.append(pattern.sub('', i))
    texto_split = texto_aux
Run Code Online (Sandbox Code Playgroud)

分裂在这里并不重要.问题是,如果我texto在最后一个方法上打印var的类型,我可能会得到str或unicode作为答案.如果文本上有任何重音,它就像unicode.所以,我得到这个错误,运行最多接收100条推文的应用程序作为答案:

UnicodeEncodeError:'ascii'编解码器无法对位置17中的字符u'\ xe9'进行编码:序数不在范围内(128)

对于以下文字:

文字:Agora oproblemaécomo speedy.输入'unicode'

有任何想法吗?

Rus*_*ove 9

看到这个页面.

decode()方法将应用于str对象,而不是unicode对象.给定一个unicode字符串作为输入,它首先尝试使用ascii编解码器将其编码为str,然后解码为utf-8,失败.

试试return normalize('NFKD', unicode(txt) ).


Eth*_*man 5

这是我在代码中用来丢弃重音等的内容.

text = unicodedata.normalize('NFD', text).encode('ascii','ignore')
Run Code Online (Sandbox Code Playgroud)

  • 为此,我得到:TypeError:必须是unicode,而不是str.因此,如下所示,我在de`normalize()`函数中添加了`unicode(text)`cast.非常感谢你! (2认同)