UnicodeEncodeError:“ascii”编解码器无法对位置37中的字符“\u201c”进行编码:序号不在范围内(128)

2024-05-18 08:35:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是从文件中读取一些引用,并使用python将它们发送到电子邮件中,但我经常遇到这样的错误(UnicodeEncodeError:'ascii'编解码器无法对字符'\u201c'进行编码,位置37:序号不在范围内(128))我如何修复它

这是密码

now = dt.datetime.now()
weekdays = now.weekday()

if weekdays == 5:
    with open("quotes.txt","r", encoding="utf8") as quote_file:
        all_quotes = quote_file.readlines()
        quote = random.choice(all_quotes)

    print(quote)

    with smtplib.SMTP("smtp.mail.yahoo.com") as connection:
        connection.starttls()
        connection.login(user=my_email, password=my_password)
        connection.sendmail(from_addr=my_email,
                            to_addrs=my_email,
                            msg=f"Subject:Monday Motivational Quote\n\n{quote}")

提前谢谢


Tags: 电子邮件emailmyas错误withpasswordall
1条回答
网友
1楼 · 发布于 2024-05-18 08:35:06

我相信你是在学习余安琪的课程。我能够让这段代码工作的唯一方法是从"quotes.txt"文件中删除""和特殊字符

您只需从第一句(或第一行)中删除它,然后将"quote"分配给all_quotes[0]即可尝试。这部分代码如下所示:

with open("quotes.txt") as quote_file:
    all_quotes = quote_file.readlines()
    quote = all_quotes[0]

一旦从每个句子中删除特殊字符,它也将与random.choice一起使用

相关问题 更多 >