Python 3.5中的注释出现Unicode错误

10

我正在使用Spyder IDE,Python 3.5版本,它是Anaconda发行版的一部分。以下是代码的前几行:

# -*- coding: utf-8 -*-
"""
Created on Tue Sep 20 16:22:40 2016

@author: pavan
This program reads csv file from the given directory .
The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo"
The output file is "comprehensive_trend.xlsx"

"""
import pdb
import pandas as pd
from datetime import date, datetime, timedelta
import os, glob
# Delarations
full_path = os.path.realpath(__file__)
current_directory = os.path.dirname(full_path)
directory = current_directory + "\\EOD from Yahoo\\"
#directory = "C:\\Users\\pavan\Documents\\Python Scripts\\EOD from Yahoo\\"

我曾在Python 2.7上运行这段代码,一切正常。最近我迁移到了Python 3.5,但是当我执行这段代码时,输出如下:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 145-146: truncated \UXXXXXXXX escape

在苦思冥想了一番后,我从注释部分中删除了这行代码:
The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo"

现在程序可以正确运行。

我的疑问:

  1. 为什么会发生这种情况?
  2. 在 Python 3.5 中编写注释,避免此类错误的最佳方法是什么?

4
在Python 3中,字符串中的\U(如在C:\Users中)有特殊含义。尝试在注释前直接添加一个"r"来告诉Python不要解释它,例如r""" ... Created on ..."""。请注意,这不会改变原始字符串的意义。 - Phillip
1
类似于https://dev59.com/O3M_5IYBdhLWcg3wgzdl - mzjn
1
请注意,“注释部分”是文档字符串,而不是注释。请参见https://dev59.com/aVsX5IYBdhLWcg3wf_r3。 - mzjn
2个回答

15

我最近第一次使用"多行注释"时遇到了类似的问题,因此我进行了一些研究。

Python 中的 "多行注释" 实际上不存在。 换句话说,它们被视为字符串(这就是为什么可以将其用作文档字符串的原因)。实际上,它们被视为没有变量的字符串。这意味着解释器无法忽略代码中的 "多行注释",因此任何特殊字符都需要转义 \

现在知道它们被视为字符串,有两种方法可以保留您的注释。

  1. 将注释转换为单行注释。在许多 IDE 中,可以进行多行转换注释(在 VScode 中按 Ctrl+K+C)。PEP8 推荐使用此方法

  2. 在多行注释块前面加上 r,表示字符串中的所有字符将以原始形式接受

来自您的代码:

r"""
Created on Tue Sep 20 16:22:40 2016

@author: pavan
This program reads csv file from the given directory .
The input directory for this is : "C:\Users\pavan\Documents\Python Scripts\EOD from Yahoo"
The output file is "comprehensive_trend.xlsx"

"""

0

您在评论中使用了\User,而\U被解释为Unicode文字,无法解码。

请改用\\User

同样地,\u应该替换为\\u

P.S. Python支持多行字符串字面量作为文档字符串,在此处的使用是完全正确和推荐的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接