如何在Python doctest中包含unicode字符串?

2024-06-02 15:30:25 发布

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

我正在研究一些必须操作unicode字符串的代码。我正试图为它写博士论文,但遇到了麻烦。下面是一个最小的示例,说明了该问题:

# -*- coding: utf-8 -*-
def mylen(word):
  """
  >>> mylen(u"áéíóú")
  5
  """
  return len(word)

print mylen(u"áéíóú")

首先,我们运行代码以查看print mylen(u"áéíóú")的预期输出。在

^{pr2}$

接下来,我们对它运行doctest来查看问题。在

$ python -m
5
**********************************************************************
File "mylen.py", line 4, in mylen.mylen
Failed example:
    mylen(u"áéíóú")
Expected:
    5
Got:
    10
**********************************************************************
1 items had failures:
   1 of   1 in mylen.mylen
***Test Failed*** 1 failures.

那么我如何测试mylen(u"áéíóú")的计算结果是5?在


Tags: 字符串代码in示例returndefunicodeutf
3条回答

如果你想要unicode字符串,你必须使用unicode docstrings!当心u!在

# -*- coding: utf-8 -*-
def mylen(word):
  u"""        <----- SEE 'u' HERE
  >>> mylen(u"áéíóú")
  5
  """
  return len(word)

print mylen(u"áéíóú")

只要测试通过,这个方法就行了。对于Python 2.x,您还需要另一种方法来使详细的doctest模式工作,或者在测试失败时获得正确的回溯:

^{pr2}$

注意!仅用于调试目的的setdefaultencoding。我可以接受它作为doctest使用,但不能在您的产品代码中的任何地方使用。在

Python 2.6.6对unicode输出的理解不太好,但可以使用以下方法解决:

  • 已经用sys.setdefaultencoding("UTF-8")描述了黑客攻击
  • unicode docstring(前面已经提到过了,非常感谢)
  • ANDprint语句。在

在我的例子中,这个docstring说明测试失败了:

def beatiful_units(*units):
    u'''Returns nice string like 'erg/(cm² sec)'.

    >>> beatiful_units(('erg', 1), ('cm', -2), ('sec', -1))
    u'erg/(cm² sec)'
    '''

带有“错误”信息

^{pr2}$

使用print我们可以修复:

def beatiful_units(*units):
    u'''Returns nice string like 'erg/(cm² sec)'.

    >>> print beatiful_units(('erg', 1), ('cm', -2), ('sec', -1))
    erg/(cm² sec)
    '''

这在Python中似乎是一个已知且尚未解决的问题。请参阅未结问题herehere。在

毫不奇怪,它可以修改为在Python 3中正常工作,因为那里的所有字符串都是Unicode:

def mylen(word):
  """
  >>> mylen("áéíóú")
  5
  """
  return len(word)

print(mylen("áéíóú"))

相关问题 更多 >