python - 在 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 看起来也很有帮助。但我觉得以前一定有人已经解决了这个问题,所以我想问一下。
解决方案
您可能想探索该tokenize
模块(python2,python3)。一个粗略的 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)
推荐阅读
- variables - 在 Netezza SQL 中传递变量名
- reactjs - 当从 redux 接收道具时,我的 PureComponent 会初始化其状态。有什么线索吗?
- amazon-web-services - 无法设置到私有 AWS API 网关 API 的 SSH 隧道
- angular - 设置选项后启用选择控制以选择上一个
- nginx - Nginx 没有提供正确的资源
- azure - 如何从 Azure VM [smalldisk] Windows Server 1809 Datacenter with Containers 卸载容器
- node.js - 我怎样才能在本地获得特定响应代码的错误?
- sql-server - SQL Server 2016 错误 4920 - ALTER TABLE {TableName} 禁用触发器 {TriggerName} 更改我的表和触发器名称
- javascript - VueJS:从未调用过计算属性的观察者
- javascript - 在 ngrx 中使用效果时的打字问题