如何替换Python中的Unicode字符?
我通过他们的API提取Twitter数据,其中一条推文有一个特殊字符(右撇号),我不断收到一个错误,说Python无法映射或字符映射该字符。我已经在互联网上搜索过了,但是我还没有找到解决这个问题的方法。我只想用Python可以识别的撇号或空字符串(基本上删除它)替换该字符。我正在使用Python 3.3。关于如何解决这个问题有什么意见吗?这看起来很简单,但我是Python的新手 编辑:下面是我用来过滤掉引发错误的unicode字符的函数如何替换Python中的Unicode字符?,python,python-3.x,unicode,Python,Python 3.x,Unicode,我通过他们的API提取Twitter数据,其中一条推文有一个特殊字符(右撇号),我不断收到一个错误,说Python无法映射或字符映射该字符。我已经在互联网上搜索过了,但是我还没有找到解决这个问题的方法。我只想用Python可以识别的撇号或空字符串(基本上删除它)替换该字符。我正在使用Python 3.3。关于如何解决这个问题有什么意见吗?这看起来很简单,但我是Python的新手 编辑:下面是我用来过滤掉引发错误的unicode字符的函数 @staticmethod def UnicodeFilt
@staticmethod
def UnicodeFilter(var):
temp = var
temp = temp.replace(chr(2019), "'")
temp = Functions.ToSQL(temp)
return temp
另外,在运行程序时,我的错误如下
“charmap”编解码器无法对位置59中的字符“\u2019”进行编码:字符映射为“未定义”
编辑:以下是我的源代码示例:
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
响应正确。您可以对unicode字符串进行编码以转换为str类型:
unicode_string = unicode(some_string, 'utf-8')
if unicode_string != some_string:
some_string = 'whatever you want it to be'
a=u"dataàçççñññ"
type(a)
a.encode('ascii','ignore')
这样,它将删除特殊字符,并返回“数据”
另一种方法是使用Unicode数据,您的程序似乎有两个问题 首先,您将错误的代码点传递到
chr()
。字符“
的十六进制代码点是0x2019
,但您要传递的是十进制数2019
(相当于十六进制中的0x7e3
)。因此,您需要执行以下任一操作:
temp = temp.replace(chr(0x2019), "'") # hexadecimal
或:
以正确替换字符
其次,出现错误的原因是程序的其他部分(可能是数据库后端)试图使用UTF-8以外的编码对unicode字符串进行编码。关于这一点很难更精确,因为你的问题中没有包含完整的回溯。但是,对“charmap”的引用表明正在使用Windows代码页(但不是cp1252);或iso编码(但不是iso8859-1,又名latin1);或者可能是KOI8_R
无论如何,处理这个问题的正确方法是确保程序的所有部分(尤其是数据库)都使用UTF-8。如果这样做,您就不必再纠结于替换字符了。您可以显示数据和代码的示例吗?感谢您添加了更多的信息,但是在不知道数据是如何获得的,或者不知道哪一行生成了错误的情况下,很难帮助您。您必须为函数“unicode()”导入一个包吗?不,您不需要。它是内置的。基本上,如果字符串不相同,那么字符串是unicode,您可以更改它Python似乎无法识别它。“未定义全局名称‘unicode’”这是我遇到的错误。您使用的是什么版本的python?正如我在最初的帖子中所说,在使用Python3.3Funcy时,我昨晚正在考虑一个类似的解决方案。我还没试过。谢谢!我尝试了你的第一个建议,所有问题都解决了。
temp = temp.replace(chr(8217), "'") # decimal