【问题标题】:Using Python to group files with similar filenames使用 Python 对具有相似文件名的文件进行分组
【发布时间】:2019-12-02 23:42:06
【问题描述】:

我正在尝试编写一个 python 脚本,该脚本在具有相似文件名的目录中查找 pdf 并组合 pdf。我要分组的文件都以相同的 16 个字符开头,但文件名中的日期不同。

所有文件名都采用这种格式:

xxxxxxxxxxxxxxx_01-01-2019.pdf
xxxxxxxxxxxxxxx_02-01-2019.pdf
xxxxxxxxxxxxxxx_03-01_2019.pdf

yyyyyyyyyyyyyyy_01-01-2019.pdf
yyyyyyyyyyyyyyy_02-01-2019.pdf

Python 脚本

import glob  
filelist = glob.glob(_filepath_) 

dictionary = {}  
for x in filelist:  
    group = dictionary.get(x[125:141],[])  
    group.append(x)  
    dictionary[x[125:141]] = group

有点有效。但是,它只为每个类似文件名返回一个文件:

['xxxxxxxxxxxxxxx_01-01-2019.pdf','yyyyyyyyyyyyyyy_01-01-2019.pdf']  

如果我能解决文件的分组问题,合并 pdf 将不成问题。

【问题讨论】:

  • 听起来像regular expressions 可能会有帮助。
  • 欢迎来到 Stack Overflow!查看tour。您需要创建一个minimal reproducible example。我想写一个答案,但似乎通配符是问题所在,而您实际上并没有给出通配符。同样,切片x[125:141] 没有意义(应该是x[:16]),并且您的输出应该是字典,而不是列表。 FWIW 循环似乎工作正常。我用你的文件名作为字符串列表对其进行了测试。
  • 是的,听起来你只需要一些基本的正则表达式。
  • @wjandrea 感谢您提供游览链接。下次一定要遵守stackoverflow的发帖规则。

标签: python pdf merge glob


【解决方案1】:

给你

filelist = glob.glob(_filepath_) 

dictionary = {}  
for x in filelist:  
    key = x[:16] # The key is the first 16 characters of the file name
    group = dictionary.get(key,[])
    group.append(x)  
    dictionary[key] = group

结果

{
'yyyyyyyyyyyyyyy_': ['yyyyyyyyyyyyyyy_01-01-2019.pdf', 'yyyyyyyyyyyyyyy_02-01-2019.pdf'],
'xxxxxxxxxxxxxxx_': ['xxxxxxxxxxxxxxx_01-01-2019.pdf', 'xxxxxxxxxxxxxxx_02-01-2019.pdf', 'xxxxxxxxxxxxxxx_03-01_2019.pdf']}

【讨论】:

  • 此解决方案有效。但是,我将密钥更改为key = os.path.basename(x).split('_')[0]
【解决方案2】:

试试这个:

import re
import glob  


filelist = glob.glob(_filepath_) 

dictionary = {} 
pattern = r'(.+)(\d{2}.\d{2}.\d{4}.pdf)'
for x in filelist:  
    tmp = re.findall(pattern, x)[0]
    if tmp[0] not in dictionary:
        dictionary[tmp[0]] = [tmp[1]]
    else:
        dictionary[tmp[0]].append(tmp[1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2017-04-03
    • 2021-02-14
    • 2020-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多