【问题标题】:Cannot save utf-8 encoded stuff in string无法将 utf-8 编码的内容保存在字符串中
【发布时间】:2013-01-24 04:24:10
【问题描述】:

我正在查询 Twitter API 并收到 utf-8 编码的答案。现在我想用format() 函数将这些答案保存在一个字符串中。这就是我到目前为止所拥有的(我已经尝试了很多替代方案)。

for user in userInfos:
    tName = user["name"] if user["name"] is not None else ""
    tLocation = user["location"] if user["location"] is not None else ""
    tProfileImageUrl = user["profile_image_url"] if user["profile_image_url"] is not None else ""
    tCreatedAt = user["created_at"] 
    tFavouritesCount = user["favourites_count"] 
    tUrl = user["url"] if user["url"] is not None else ""
    tId = user["id"] 
    tProtected = user["protected"] 
    tFollowerCount = user["followers_count"]
    tLanguage = user["lang"]
    tVerified = user["verified"]
    tGeoEnabled = user["geo_enabled"]
    tTimeZone = user["time_zone"] if user["time_zone"] is not None else ""
    tFriendsCount = user["friends_count"]
    tStatusesCount = user["statuses_count"]
    tScreenName = user["screen_name"]

    # Custom characteristics
    age = utl.get_age_in_years(birthdayDict[str(tId)])

    # Follower-friend-ratio
    if tFriendsCount > 0:
        foRatio = float(tFollowerCount)/float(tFriendsCount)
    else:
        foRatio = ""

    # Age of account in weeks
    numWeeks = utl.get_age_in_weeks(tCreatedAt)

    # Tweets per time
    tweetsPerWeek = float(tStatusesCount) / numWeeks
    tweetsPerDay = tweetsPerWeek / 7.0

    in_users.remove(str(tId))

    outputList = [str(tName),
                  str(tScreenName),
                  str(tProfileImageUrl),
                  str(tLocation),
                  str(tCreatedAt),
                  str(tUrl),
                  str(age),
                  str(tStatusesCount),
                  str(tFollowerCount),
                  str(tFriendsCount),
                  str(tFavouritesCount),
                  str(foRatio),
                  str(tLanguage),
                  str(tVerified),
                  str(tGeoEnabled),
                  str(tTimeZone),
                  str(tProtected),
                  str(numWeeks),
                  str(tweetsPerWeek),
                  str(tweetsPerDay)]

    pprint.pprint(outputList)
    fOut.write("{}{}{}{}{}{}{}\n".format(twitterUsers[str(tId)], outputDelimiter, outputDelimiter.join(outputList), outputDelimiter, utl.get_date(), outputDelimiter, utl.get_time()))
当 tName/tLocation 包含诸如 \xe4 之类的内容时,

str(tName)、str(tLocation) 等会给我错误

ERROR:__main__:'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)
Traceback (most recent call last):
  File "../code/userinfo_extraction_old.py", line 167, in <module>
    outputList = [str(tName),
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 10: ordinal not in range(128)

我试图了解它是如何工作的,但我无法弄清楚这里出了什么问题。我也尝试过使用 unicode() 而不是 str()...没有机会。

【问题讨论】:

  • ...你正在运行 Python 2.something?
  • 是的,Python 2.7,忘了说,抱歉。
  • 试试 str = str.decode('utf-8')
  • 你的意思是我应该把它放在我所有的 str 调用之上,意思是覆盖默认的 str 函数?或做类似str(tName.decode('utf-8'))的事情?

标签: python string unicode utf-8 python-2.7


【解决方案1】:

要将unicode 数据转换为str,您需要指定编码。使用tName.encode('utf8')等

您可能想了解 Python 和 Unicode:

【讨论】:

  • 非常感谢。是的,我之前可能读过其中的一两个文档,但由于那个话题太无聊了,一周后我总是会忘记一半的东西……但无论如何感谢您的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
  • 2011-08-09
  • 2019-11-03
  • 2020-11-29
  • 2014-01-18
  • 2020-04-07
  • 2016-01-11
相关资源
最近更新 更多