首页 > 解决方案 > 在 Python 中查找/测试未修饰的字符串文字(没有 b" 或 u")

问题描述

作为编写在 Python 2 和 3 上一致工作的代码的一部分,我想测试任何未经修饰的字符串文字(任何开头的 " 或 ' 前面没有 ab 或 u)。

我很擅长编写测试用例,所以我只需要一个函数,它可以在我的 .py 文件中返回所有未修饰的字符串文字。

例如,假设我有包含以下内容的 Python 代码:

example_byte_string = b'这是一个 ASCII 文本或字节的字符串'

example_unicode_string = u"这是一个 Unicode 字符串"

example_unadorned_string = '这个字符串没有被标记,在 Python 2 中将被视为字节,但在 Python 3 中被视为 Unicode'

example_unadorned_string2 = "这就是他们所说的'字符串'!"

example_unadorned_string3 = '约翰说“真的吗?” 非常响亮地'

我想找到所有未显式标记的字符串,例如 example_unadorned_string,以便我可以正确标记它们,从而使它们在 Python 2 和 3 中运行时的行为方式相同。在字符串中容纳引号也很好,例如 example_unadorned_string2 和 3,因为它们不应该将 u/b 添加到内部引号中。显然,从长远来看,我们将放弃对 Python 2 的支持,并且只有字节需要显式标记。这与 python-future.org 推荐的方法一致:http: //python-future.org/automatic_conversion.html#separating-text-from-bytes

我可以想出用非常讨厌的 grep 来做到这一点的方法。AST 看起来也很有帮助。但我觉得以前一定有人已经解决了这个问题,所以我想问一下。

标签: pythontestingstring-literalspython-2to3

解决方案


您可能想探索该tokenize模块(python2python3)。一个粗略的 Python 3 示例是这样的:

import tokenize
import token

def iter_unadorned_strings(f):
    tokens = tokenize.tokenize(f.readline)
    for t in tokens:
        if t.type == token.STRING and t.string[0] in ['"', "'"]:
            yield t

fname = r'code_file.py'
if __name__ == '__main__':
    with open(fname, 'rb') as f:
        for s in iter_unadorned_strings(f):
            print(s.start, s.end, s.string)

推荐阅读