如何计算Python中匹配文件的数量?

时间:2015-08-30 06:10:56

标签: python file

我的文件名如下:

  • 文件001-001.dat
  • 文件001-002.dat
  • 文件001-003.dat
  • 文件001-004.dat
  • 文件001-005.dat

  • 文件002-001.dat

  • 文件002-002.dat
  • 文件002-003.dat
  • 文件002-004.dat

  • 文件003-001.dat

  • 文件003-002.dat
  • 文件003-003.dat
  • 文件003-004.dat
  • 文件003-005.dat
  • 文件003-006.dat
  • 文件003-007.dat
  • 文件003-008.dat

  • 文件999-010.dat

我正在尝试计算相同第一个数字的文件数,例如代码应该给我以001开头的文件数量为5,002为4,... 999为1。

我已设法使用此代码完成此操作,该代码计算'file_count'文件夹中的文件:

from collections import Counter
import numpy as np
import os
import re
data_folders = []
data_files = []
for root, directories, files in sorted(os.walk('./file_count')):
    files = sorted([f for f in files if os.path.splitext(f)[1] in ('.dat,')])
    for file in files:
        data_folders.append(root)
        data_files.append((re.findall(r"[-+]?\d*\.\d+|\d+", file)[-2].zfill(3), re.findall(r"[-+]?\d*\.\d+|\d+", \
            file)[-1].zfill(3), os.path.join(root, file)))
data_folders = np.unique(data_folders)
data_files = sorted(data_files)
a = np.array(data_files)
print a[:, 0]
c = Counter(a[:, 0])
print c['001']

是否有比这更简单有效的代码?任何可以解决这个问题的内置函数?

4 个答案:

答案 0 :(得分:1)

您可以使用os.listdir(),它将您的文件名作为字符串列表返回。

接下来,使用re.match和list comprehension获取要分组的数字字符串列表。

>>> stt = 'file-001-003.dat'
>>> import re
>>> k = re.match(r'.*?-(\d*?)-.*',stt)
>>> k.group(1)
'001'

最后,使用groupby模块获取相同数字字符串的计数。

对于groupby,请参阅此SO:How to count the frequency of the elements in a list?

答案 1 :(得分:0)

当您在问题中添加R标记时(不确定原因),这里有一个可能的R解决方案:

table(sub('file-([0-9]{3})-[0-9]{3}.dat', '\\1', list.files()))

如果目录中还有其他文件,则将该正则表达式作为pattern的{​​{1}}参数传递,仅列出相关文件。

答案 2 :(得分:0)

以下方法应该有效:

for k, g in itertools.groupby(files, key=lambda x:re.search('-(\d+)-', x).group(1)):
    print k, len(list(g))

这会显示:

001 5
002 4
003 8
999 1

答案 3 :(得分:0)

这样的东西
import re, collections

file_regex = re.compile('^file-(\d{3})-(\d{3}).dat$')
matches = [file_regex.match(f) for root, dirs, files in \
    os.walk("./file_count") for f in files if file_regex.match(f)]
c = collections.Counter(match.groups()[0] for match in matches)