[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 32: ordinal not in range(128)
[英]UnicodeEncodeError: 'ascii' codec can't encode character '\u2019'
當我嘗試將 Twitter 推文發送到電子郵件時收到一條錯誤消息。 錯誤信息是:
UnicodeEncodeError: 'ascii' 編解碼器無法對位置 114 中的字符 '\’' 進行編碼:序號不在范圍內 (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"
)
任何解決字符“\’”問題的建議。 謝謝。
排序
我使用以下代碼:
進口重新
tweeter = re.sub(r'[^\\x00-\\x7f]',r' ',tweeter)
並修復了腳本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.