【问题标题】:Invalid Syntax Error On Simple Integer Assignment [closed]简单整数分配的无效语法错误[关闭]
【发布时间】:2014-05-02 01:44:10
【问题描述】:

我想我遇到了编码问题。当我更改为 utf-16 时,错误变为第一行“导入温度”

我安装 Python 3.x 时认为可能是版本问题,但症状相同。

我一直在运行的其他练习脚本运行良好。有什么想法吗?

Python 表示语法错误发生在“temp = 0”

##### modules.py 文件
import temperature

temp = 212
convTemp = temperature.ftoc(temp)
print("The converted temp is " + str(convTemp))
temp = 0
convTemp = temperature.ctof(temp)
print("The converted temp is " + str(convTemp))
#### temperature.py 文件内容
def ftoc(temp):
    return (5.0/9.0) * (temp - 32.0)

def ctof(temp):
    return (9.0/5.0) * temp + 32.0
更正原始帖子中的代码后的结果。
hostname$ python modules.py
Traceback (most recent call last):
  File "modules.py", line 1, in <module>
    import temperature
  File "/Users/[myusername]/Dropbox/python/temperature.py", line 1
SyntaxError: Non-ASCII character '\xfe' in file /Users/[myusername]/Dropbox/python/temperature.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
hostname$

【问题讨论】:

  • 您在上一行缺少右括号。

标签: python variables syntax integer variable-assignment


【解决方案1】:

确实,这似乎是编码问题。 \xFEBOM(\xFE \xFF) 的一部分,用于 UTF-16 编码。

使用 UTF-16 作为 Python 源代码不是一个好主意。您无法使用编码标记向 Python 解析器提示源文件的源代码编码。比如

# encoding: utf-8

详细解释见PEP-0263,以下是部分重要信息:

允许以上述方式处理前两行的任何编码都允许作为源代码编码,这包括与 ASCII 兼容的编码以及某些多字节编码,例如 Shift_JIS。它不包括对所有字符使用两个或更多字节的编码,例如UTF-16。这样做的原因是为了让分词器中的编码检测算法保持简单。

【讨论】:

    【解决方案2】:
    from temperature import ftoc
    from temperature import ctof
    

    这是多余的,因为您导入了所有温度函数

    import temperature
    

    您有语法错误,打印语句末尾缺少括号。

    当你想要str(convTemp) 时,你也有str(temperature)。解决这些问题,我认为它会正常工作。

    【讨论】:

    • 这很尴尬。对不起。漫长的一天。这是编码错误似乎变得更加明显的地方。
    • 'code'hostname$ python modules.py Traceback(最近一次调用最后):文件“modules.py”,第 1 行,在 导入温度文件“/Users/[myusername]/ Dropbox/python/temperature.py", line 1 SyntaxError: Non-ASCII character '\xfe' in file /Users/[myusername]/Dropbox/python/temperature.py on line 1,但未声明编码;有关详细信息,请参阅python.org/peps/pep-0263.html 主机名$
    • 修改后的程序对我有用,只是从您的问题中复制粘贴并在文本编辑器中编辑您的内容 - 我没有遇到编码错误。
    • 默认使用带有 UTF-8 的 TextWrangler。我在使用 requests 模块时遇到了类似的错误,直到遇到要导入 sys 的线程;重新加载(系统); sys.setdefaultencoding("utf-8") 解决了我的问题,但似乎有点多。
    • 你只是少了一个括号。不要为更改默认编码而烦恼。这只会在 Python 2.X 上期望默认为 ascii 的库导致更多问题。在 3.X 上,utf-8 已经是默认值了。
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2017-05-25
    • 2020-07-02
    • 2014-07-17
    • 2012-12-21
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多