在 Travis 上 运行 测试时语法无效

Invalid syntax while running test on Travis

我在每次提交时都遇到了 Travis 的问题。我的测试在本地工作,但在 Travis 上我收到此错误:

Traceback (most recent call last):
  File "/opt/python/3.2.5/lib/python3.2/unittest/case.py", line 370, in _executeTestPart
    function()
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 32, in testFailure
    raise exception
ImportError: Failed to import test module: test.test_parser
Traceback (most recent call last):
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 261, in _find_tests
    module = self._get_module_from_name(name)
  File "/opt/python/3.2.5/lib/python3.2/unittest/loader.py", line 239, in _get_module_from_name
    __import__(name)
  File "/home/travis/build/davidmogar/genderator/test/test_parser.py", line 5, in <module>
    import genderator
  File "/home/travis/build/davidmogar/genderator/genderator/__init__.py", line 3, in <module>
    from genderator.parser import Parser
  File "/home/travis/build/davidmogar/genderator/genderator/parser.py", line 5, in <module>
    from .utils import Normalizer
  File "/home/travis/build/davidmogar/genderator/genderator/utils.py", line 63
    u'\N{COMBINING TILDE}'
                        ^
SyntaxError: invalid syntax

这是该行所在的代码:

def remove_accent_marks(text):
        good_accents = {
            u'\N{COMBINING TILDE}',
            u'\N{COMBINING CEDILLA}'
        }

        return ''.join(c for c in unicodedata.normalize('NFKD', text)
                       if unicodedata.category(c) != 'Mn' or c in good_accents)

我不知道问题出在哪里,因为正如我所说,所有测试都在本地进行。这是我的 .travis.yml 文件:

language: python
python:
  - "3.2"
  - "3.3"
  - "3.4"
script: python -m unittest discover

有什么想法吗?

Python 3 中的 u'...' 语法仅在 Python 3.3 and up 中受支持。

u 前缀只是为了支持多语言 Python 代码(同时支持 2 和 3),如果不需要支持 Python 可以安全地删除2.

如果您需要同时支持 Python 2 3.2,则必须使用不同的方法。您可以使用 from __future__ 导入来使 Python 2 中的所有字符串文字生成 unicode 字符串对象;这适用于每个模块:

from __future__ import unicode_literals

def remove_accent_marks(text):
    good_accents = {
        '\N{COMBINING TILDE}',
        '\N{COMBINING CEDILLA}'
    }

字符串将在 Python 2 和 3 中被视为 Unicode。

或者您可以创建自己的多语言函数:

import sys

if sys.version_info[0] < 3:
    u = lambda s: unicode(s.replace(r'\', r'\\'), "unicode_escape")
else:
    u = lambda s: s

并在所有 Unicode 字符串上使用它:

def remove_accent_marks(text):
    good_accents = {
        u('\N{COMBINING TILDE}'),
        u('\N{COMBINING CEDILLA}')
    }

或者您可以使用 six library 为您生成该桥:

import six

def remove_accent_marks(text):
    good_accents = {
        six.u('\N{COMBINING TILDE}'),
        six.u('\N{COMBINING CEDILLA}')
    }

您可能想阅读 Python Porting HOWTO