【问题标题】:How can I replace Unicode characters in Python?如何在 Python 中替换 Unicode 字符?
【发布时间】:2016-07-04 16:27:52
【问题描述】:

我正在通过他们的 API 提取 Twitter 数据,其中一条推文有一个特殊字符(右撇号),我不断收到错误消息,说 Python 无法映射或字符映射该字符。我已经查看了整个互联网,但我还没有找到解决这个问题的方法。我只想用 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's 响应正确。

【问题讨论】:

  • 你能展示一个数据样本和你的代码吗?
  • 感谢您添加 一点 更多信息,但不知道您是如何获得数据的,也不知道究竟是哪一行产生了错误,这很难提供帮助。

标签: python python-3.x unicode


【解决方案1】:

您的程序似乎有两个问题。

首先,您将错误的代码点传递给chr()。字符hexdecimal 代码点是0x2019,但您传递的是decimal 数字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。如果你这样做了,你就不必再为替换字符而烦恼了。

【讨论】:

  • 有趣的是,我昨晚正在考虑类似的解决方案。不过还没来得及尝试。
  • 谢谢!我尝试了您的第一个建议,所有问题都已解决。
【解决方案2】:

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

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

这样删除特殊字符会返回“数据”。

您可以使用 unicodedata 的其他方式

【讨论】:

    【解决方案3】:
    unicode_string = unicode(some_string, 'utf-8')
    if unicode_string != some_string:
        some_string = 'whatever you want it to be'
    

    【讨论】:

    • 你必须为函数'unicode()'导入一个包吗?
    • 不,你没有。它是内置的。基本上如果字符串不一样,那么字符串是unicode,你可以改变它
    • Python 似乎无法识别它。 “未定义全局名称'unicode'”这是我遇到的错误。
    • 你用的是什么版本的python? dropbox.com/s/7cb1n8pqxfj0bu7/…
    • 正如我在原帖中所说,在使用 Python 3.3 时
    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多