【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 37: ordinal not in range(128) [duplicate]UnicodeEncodeError:“ascii”编解码器无法在位置 37 编码字符“\u201c”:序数不在范围内(128)[重复]
【发布时间】:2021-01-16 12:04:33
【问题描述】:

我只是从文件中读取一些引号并使用 python 在我的电子邮件中发送它们,但我经常面临这个问题(UnicodeEncodeError: 'ascii' codec can't encode character '\u201c' in position 37: ordinal not in range(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}")

提前致谢。

【问题讨论】:

  • msg=f"Subject:Monday Motivational Quote\n\n{quote}".encode("utf8") 在最后一行使用 .encode() 方法

标签: python


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 2018-06-29
    • 2017-12-18
    • 2013-11-18
    • 2016-10-06
    • 2020-04-04
    • 2019-11-10
    • 2021-05-14
    • 2023-03-03
    相关资源
    最近更新 更多