【问题标题】:Test whether a file name has the correct naming convention in Python在 Python 中测试文件名是否具有正确的命名约定
【发布时间】:2012-11-19 20:51:35
【问题描述】:

如何在 Python 中测试文件名是否具有正确的命名约定?假设我希望文件名以字符串_v 结尾,然后是某个数字,然后是.txt。我该怎么做?我有一些示例代码表达了我的想法,但实际上并不起作用:

fileName = 'name_v011.txt'
def naming_convention(fileName):
    convention="_v%d.txt"
    if fileName.endswith(convention) == True:
        print "good"
    return
naming_convention(fileName)

【问题讨论】:

    标签: python nomenclature


    【解决方案1】:

    您可以使用 Python 的 re module 使用正则表达式:

    import re
    
    if re.match(r'^.*_v\d+\.txt$', filename):
        pass  # valid
    else:
        pass  # invalid
    

    让我们把正则表达式分开:

    • ^ 匹配字符串的开头
    • .* 匹配任何东西
    • _v 匹配 _v 字面意思
    • \d+ 匹配一位或多位数字
    • \.txt 匹配 .txt 字面意思
    • $ 匹配字符串的结尾

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 2016-05-24
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多