【发布时间】:2021-04-19 00:44:03
【问题描述】:
我正在尝试编写一个用于生成 python 类的 CLI。其中一部分需要验证用户输入中提供的标识符,而对于 python,这需要确保标识符符合标识符的 pep8 最佳实践/标准 - 具有 CapsCases 的类、具有 all_lowercase_with_underscores 的字段、具有等等的包和模块等等 -
# it is easy to correct when there is a identifier
# with underscores or whitespace and correcting for a class
def package_correct_convention(item):
return item.strip().lower().replace(" ","").replace("_","")
但是当标记之间没有空格或下划线时,我不确定如何正确地将标识符中每个单词的首字母大写。是否可以在不使用 AI 或类似的东西的情况下实现类似的东西:
比如说:
# providing "ClassA" returns "classa" because there is no delimiter between "class" and "a"
def class_correct_convention(item):
if item.count(" ") or item.count("_"):
# checking whether space or underscore was used as word delimiter.
if item.count(" ") > item.count("_"):
item = item.split(" ")
elif item.count(" ") < item.count("_"):
item = item.split("_")
item = list(map(lambda x: x.title(), item))
return ("".join(item)).replace("_", "").replace(" ","")
# if there is no white space, best we can do it capitalize first letter
return item[0].upper() + item[1:]
【问题讨论】:
-
提供
ClassA实际上返回ClassA。您能否提供一个清晰的示例(或一些使问题清晰的示例),以及预期的结果以及与实际结果有何不同?此外,显然需要有一些区分标记,如大写。毕竟,'classa' 真的是 'ClassA' 还是作者打算使用 'ClasSa' 或 'Classa'(用任何可能意味着什么的语言)? -
你基本上需要一个分词器和一个接受词的字典。它需要回溯。而且它总是启发式的,因为有有效的字符串可以以不止一种方式进行标记,例如
hislap是否应该标记为hiSlap或hisLap?旁注:Python 已经提供了str.capitalize和str.title方法,它们可以为您完成很多工作,因此您可能需要研究它们。
标签: python conventions pep8