繁体   English   中英

如何在Python中替换Unicode字符?

[英]How can I replace Unicode characters in Python?

我通过他们的API提取Twitter数据,其中一条推文有一个特殊字符(右撇号),并且我不断收到错误消息,指出Python无法映射或字符映射该字符。 我已经遍及整个Internet,但尚未找到解决此问题的解决方案。 我只想用Python可以识别的撇号或一个空字符串(基本上将其删除)替换该字符。 我正在使用Python 3.3。 关于如何解决此问题的任何意见? 看起来似乎很简单,但是我是Python的新手。

编辑:这是我用来尝试滤除引发错误的Unicode字符的函数。

@staticmethod
def UnicodeFilter(var):
    temp = var
    temp = temp.replace(chr(2019), "'")
    temp = Functions.ToSQL(temp)
    return temp

另外,在运行程序时,我的错误如下。

'charmap'编解码器无法在位置59编码字符'\\ u2019':字符映射为'undefined'

编辑:这是我的源代码的示例:

import json
import mysql.connector
import unicodedata
from MySQLCL import MySQLCL

class Functions(object):
"""This is a class for Python functions"""

@staticmethod
def Clean(string):
    temp = str(string)
    temp = temp.replace("'", "").replace("(", "").replace(")", "").replace(",", "").strip()
    return temp

@staticmethod
def ParseTweet(string):
    for x in range(0, len(string)):
        tweetid = string[x]["id_str"]
        tweetcreated = string[x]["created_at"]
        tweettext = string[x]["text"]
        tweetsource = string[x]["source"]
        truncated = string[x]["truncated"]
        inreplytostatusid = string[x]["in_reply_to_status_id"]
        inreplytouserid = string[x]["in_reply_to_user_id"]
        inreplytoscreenname = string[x]["in_reply_to_screen_name"]
        geo = string[x]["geo"]
        coordinates = string[x]["coordinates"]
        place = string[x]["place"]
        contributors = string[x]["contributors"]
        isquotestatus = string[x]["is_quote_status"]
        retweetcount = string[x]["retweet_count"]
        favoritecount = string[x]["favorite_count"]
        favorited = string[x]["favorited"]
        retweeted = string[x]["retweeted"]
        possiblysensitive = string[x]["possibly_sensitive"]
        language = string[x]["lang"]

        print(Functions.UnicodeFilter(tweettext))
        #print("INSERT INTO tweet(ExTweetID, TweetText, Truncated, InReplyToStatusID, InReplyToUserID, InReplyToScreenName, IsQuoteStatus, RetweetCount, FavoriteCount, Favorited, Retweeted, Language, TweetDate, TweetSource, PossiblySensitive) VALUES (" + str(tweetid) + ", '" + Functions.UnicodeFilter(tweettext) + "', " + str(truncated) + ", " + Functions.CheckNull(inreplytostatusid) + ", " + Functions.CheckNull(inreplytouserid) + ", '" + Functions.CheckNull(inreplytoscreenname) + "', " + str(isquotestatus) + ", " + str(retweetcount) + ", " + str(favoritecount) + ", " + str(favorited) + ", " + str(retweeted) + ", '" + str(language) + "', '" + Functions.ToSQL(tweetcreated) + "', '" + Functions.ToSQL(tweetsource) + "', " + str(possiblysensitive) + ")")
        #MySQLCL.Set("INSERT INTO tweet(ExTweetID, TweetText, Truncated, InReplyToStatusID, InReplyToUserID, InReplyToScreenName, IsQuoteStatus, RetweetCount, FavoriteCount, Favorited, Retweeted, Language, TweetDate, TweetSource, PossiblySensitive) VALUES (" + str(tweetid) + ", '" + tweettext + "', " + str(truncated) + ", " + Functions.CheckNull(inreplytostatusid) + ", " + Functions.CheckNull(inreplytouserid) + ", '" + Functions.CheckNull(inreplytoscreenname) + "', " + str(isquotestatus) + ", " + str(retweetcount) + ", " + str(favoritecount) + ", " + str(favorited) + ", " + str(retweeted) + ", '" + language + "', '" + tweetcreated + "', '" + str(tweetsource) + "', " + str(possiblysensitive) + ")")

@staticmethod
def ToBool(variable):
    if variable.lower() == 'true':
        return True
    elif variable.lower() == 'false':
        return False

@staticmethod
def CheckNull(var):
    if var == None:
        return ""
    else:
        return var

@staticmethod
def ToSQL(var):
    temp = var
    temp = temp.replace("'", "''")
    return str(temp)

@staticmethod
def UnicodeFilter(var):
    temp = var
    #temp = temp.replace(chr(2019), "'")
    unicodestr = unicode(temp, 'utf-8')
    if unicodestr != temp:
        temp = "'"
    temp = Functions.ToSQL(temp)
    return temp

ekhumoro的回答是正确的。

您的程序似乎存在两个问题。

首先,您将错误的代码点传递给chr() 字符的代码hexdecimal'0x2019 ,但你传递的十进制2019 (这相当于0x7e3十六进制)。 因此,您需要执行以下任一操作:

    temp = temp.replace(chr(0x2019), "'") # hexadecimal

要么:

    temp = temp.replace(chr(8217), "'") # decimal

为了正确替换字符。

其次,出现错误的原因是因为程序的其他部分(可能是数据库后端)正在尝试使用UTF-8以外的其他编码来编码unicode字符串。 很难对此进行更精确的描述,因为您没有在问题中包括完整的追溯。 但是,对“ charmap”的引用表明正在使用Windows代码页(而不是cp1252)。 或iso编码(但不是iso8859-1,又名latin1); 或可能是KOI8_R。

无论如何,解决此问题的正确方法是确保程序的所有部分(尤其是数据库)都使用UTF-8。 如果这样做,您将不必再为替换字符而烦恼了。

您可以对您的unicode字符串进行编码以转换为str类型:

 a=u"dataàçççñññ"
type(a)
a.encode('ascii','ignore')

这样,它将删除特殊字符将返回“数据”。

您可以使用unicodedata的其他方式

unicode_string = unicode(some_string, 'utf-8')
if unicode_string != some_string:
    some_string = 'whatever you want it to be'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM