【问题标题】:Extracting year from the name of the file from the last index before the extention in python从python中扩展名之前的最后一个索引中的文件名中提取年份
【发布时间】:2021-07-25 05:31:20
【问题描述】:

我正在尝试从文件名中提取年份。 我有文件,命名为

godzilla_2012.txt

king_arthur_legend_of_the_sword_2016.txt

Teenage_Mutant_ninja_turtle_2017.txt

我想从文件名中提取年份,例如

2012

2016

等等

【问题讨论】:

标签: python file split


【解决方案1】:

你可以试试这个。如果您想将它用于多个语句,您可以在之后迭代使用它。

statement = 'king_arthur_legend_of_the_sword_2016.txt'
year = statement.split('.')[0].split('_')[-1]

【讨论】:

    【解决方案2】:

    您可以在这里使用re.findall

    inp = ["godzilla_2012.txt", "king_arthur_legend_of_the_sword_2016.txt", "Teenage_Mutant_ninja_turtle_2017.txt"]
    years = [re.findall(r'(\d{4})\.\w+$', x)[0] for x in inp]
    print(years)  # ['2012', '2016', '2017']
    

    【讨论】:

      【解决方案3】:

      如果始终是这种格式,您可以使用filename.split('_')[-1].split('.')[0]。那将给出字符串;如果你想要它作为一个整数,你可以做int(filename.split('_')[-1].split('.')[0])

      正则表达式更强大,可以让您处理更广泛的格式,但这可能是一件坏事。例如,如果您有一个正则表达式来查找任何数字字符,它将在wonder_woman_1984_2020.txt 中选择19842001_a_space_odyssey_1968.txt 中的2001

      【讨论】:

      • 看来another user已经提供了这个解决方案。
      • 谢谢你,这是一个非常详细的例子,将来可能会用你的解决方案来反驳它。
      【解决方案4】:

      如果file_name在您的文件中没有年份之前的数字,您可以通过此方法获取年份

      file = "file6655"
      n = 0
      li = ["0","1","2","3","4","5","6","7","8","9"]
      for i in file:
          if i in li:
              n = n + 1
              if n == 1:
                  year = i
              if n > 1:
                  year = year + i
              print(year)
      

      输出将是 6655。 对于文件夹中的多个文件,您可以使用 os 模块

      【讨论】:

        猜你喜欢
        • 2010-10-07
        • 1970-01-01
        • 2013-09-17
        • 2013-07-10
        • 2018-10-27
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多