【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character '\u2019'UnicodeEncodeError:“ascii”编解码器无法编码字符“\u2019”
【发布时间】:2021-09-28 18:47:50
【问题描述】:

当我尝试将 Twitter 推文发送到电子邮件时,我收到一条错误消息。错误信息是:

UnicodeEncodeError: 'ascii' codec can't encode character '\u2019' in position 114: ordinal not in range(128)

我的代码如下:


# Python 3.9

import smtplib, requests
import datetime as datetime

# twitter api function (not shown) retrieves a series of tweets - these are added to a dictionary (below)


tweets = {'climate change': 'Eco1stArt - USATeam Animal rides to the rescue in nine-year-old Zac’s latest book about the climate change emergency #books -  twitter short URL  \ncaykahvekeyfi - istanbultwitter short URL\nMaura2e2_ - Killaloe Co. Clare????????Éire????????Politicians refusing to treat the #ClimateEmergency as an emergency are committing crimes against humanity.twitter short URL\n"}

# I cant show the actual twitter short URLs in teh tweet data - 
# code to convert the dictionary into a formatted string

tweeter = ""
for k, v in tweets.items():
    tweeter += f"\n{k}\n"
    tweeter += f"{v}"

# code to build and send the email

subject = "Todays Tweets.."
email_address = "miles-s@hotmail.co.uk"

curr_date = get_date()
my_email = "email@email.com"
PW = "mypassword"
Gmail = "smtp.service.com"
with smtplib.SMTP("smtp.service.com", port=587) as connection:
    connection.starttls() # decures the email message
    connection.login(user=my_email, password = PW)
    connection.sendmail(
        from_addr=my_email,
        to_addrs=email_address,
        msg=f"Subject:{subject}\n\n{message}\n"
    )

解决字符“\u2019”问题的任何建议。谢谢。

【问题讨论】:

  • 您是否尝试在sendmailmail_options 参数中使用SMTPUTF8
  • 我也会试试这个选项。谢谢

标签: python api twitter


【解决方案1】:

排序

我使用以下代码:

重新导入

高音 = re.sub(r'[^\x00-\x7f]',r' ',高音)

这修正了脚本。

【讨论】:

  • 所以您不想发送全文,而只想发送非常有限的 ASCII 集中的那些字符?
  • 不,我想发送带有 twitter URL 的文本。似乎现在可以工作了。
猜你喜欢
  • 1970-01-01
  • 2015-10-21
  • 2010-12-11
  • 2012-07-02
  • 2010-12-11
  • 2017-02-01
  • 1970-01-01
相关资源
最近更新 更多