1

How would I write a function in Python to determine if a list of filenames matches a given pattern and which files are missing from that pattern? For example:

Input ->

KUMAR.3.txt
KUMAR.4.txt
KUMAR.6.txt
KUMAR.7.txt
KUMAR.9.txt
KUMAR.10.txt
KUMAR.11.txt
KUMAR.13.txt
KUMAR.15.txt
KUMAR.16.txt

Desired Output-->

KUMAR.5.txt
KUMAR.8.txt
KUMAR.12.txt
KUMAR.14.txt

Input -->

KUMAR3.txt
KUMAR4.txt
KUMAR6.txt
KUMAR7.txt
KUMAR9.txt
KUMAR10.txt
KUMAR11.txt
KUMAR13.txt
KUMAR15.txt
KUMAR16.txt

Desired Output -->

KUMAR5.txt
KUMAR8.txt
KUMAR12.txt
KUMAR14.txt
4

2 回答 2

2

您可以这样处理:

  1. 将文件名转换为适当的整数。
  2. 找出缺失的数字。
  3. 将缺失的数字与文件名模板结合起来作为输出。

对于(1),如果文件结构是可预测的,那么这很容易。

def to_num(s, start=6):
    return int(s[start:s.index('.txt')])

鉴于:

lst = ['KUMAR.3.txt', 'KUMAR.4.txt', 'KUMAR.6.txt', 'KUMAR.7.txt',
       'KUMAR.9.txt', 'KUMAR.10.txt', 'KUMAR.11.txt', 'KUMAR.13.txt',
       'KUMAR.15.txt', 'KUMAR.16.txt']

您可以通过以下方式获取已知号码列表:map(to_num, lst)。当然,要寻找差距,你只需要最小值和最大值。将它与range函数结合起来,你会得到所有你应该看到的数字,然后删除你已经得到的数字。套装在这里很有帮助。

def find_gaps(int_list):
    return sorted(set(range(min(int_list), max(int_list))) - set(int_list))

把它们放在一起:

missing = find_gaps(map(to_num, lst))
for i in missing:
    print 'KUMAR.%d.txt' % i
于 2009-04-15T02:59:26.710 回答
1

假设模式是相对静态的,这很容易使用正则表达式:

import re

inlist = "KUMAR.3.txt KUMAR.4.txt KUMAR.6.txt KUMAR.7.txt KUMAR.9.txt KUMAR.10.txt KUMAR.11.txt KUMAR.13.txt KUMAR.15.txt KUMAR.16.txt".split()

def get_count(s):
    return int(re.match('.*\.(\d+)\..*', s).groups()[0])

mincount = get_count(inlist[0])
maxcount = get_count(inlist[-1])
values = set(map(get_count, inlist))
for ii in range (mincount, maxcount):
    if ii not in values:
        print 'KUMAR.%d.txt' % ii
于 2009-04-15T02:46:38.427 回答