ipython,找到特定的目录

时间:2017-06-20 17:11:20

标签: python ipython

我在ipython 5.1.0中做了一些(初学者)编程。

大约有100个目录名称如 volatile,只有数字正在发生变化。

我使用import pygame from pygame.locals import * from pygame import Surface def getColumn(surface, index): assert index <= surface.get_width(), "index can't be bigger, than surface width" height = surface.get_height() subsurf = Surface((1,height)) # Create Surface 1 px by picture-height high, to store the output in subsurf.blit(surface.subsurface(pygame.Rect( (index,0),(1,height) )),(0,0)) # Blit a one pixel width subsurface with x Position at index of the image to subsurf return subsurf def shiftRightDown(surface, pixels): size = surface.get_size() newSize = (size[0], size[1]+pixels) coeff = pixels / size[0] returnSurface = Surface(newSize) for i in range(size[1]): # here happens the magic returnSurface.blit(getColumn(surface, i), (i,0+int(i*coeff))) return returnSurface 将名称读入程序。 现在我需要所有目录,其中前两个数字(Mix_XFUEL_0.5_XOXID_0.6_PHI_0.2fnmatch之后)相同,如:

XFUEL

但也

XOXID

我试过了:

Mix_XFUEL_0.5_XOXID_0.5_PHI_0.2
Mix_XFUEL_0.5_XOXID_0.5_PHI_0.4
Mix_XFUEL_0.5_XOXID_0.5_PHI_0.6

但它不起作用。

怎么做?

2 个答案:

答案 0 :(得分:0)

import os, re
from collections import defaultdict

results = defaultdict(list)
for file in os.listdir('/path/to/your/directory'):
    m = re.match(r'Mix_XFUEL_(.*?)_XOXID_(.*?)_PHI_.*', file)
    if m:
        numbers = m.group(1,2)
        results[numbers].append(file)

for r in results:
    print(results[r])

答案 1 :(得分:0)

使用正则表达式,第二个捕获组(\1)断言它需要匹配第一个捕获组(\d+(?:\.\d+)?)

(\d+(?:\.\d+)?)匹配任何十进制数或带小数点的数字

import re
re.match(r'Mix_XFUEL_(\d+(?:\.\d+)?)_XOXID_(\1)_PHI', infile)

这将匹配

  • &#34; Mix_XFUEL_0.5_XOXID_0.5_PHI_0.2&#34;
  • &#34; Mix_XFUEL_0.6_XOXID_0.6_PHI_0.2&#34;
  • &#34; Mix_XFUEL_5_XOXID_5_PHI_0.2&#34;

但不是

  • &#34; Mix_XFUEL_0.5_XOXID_0.6_PHI_0.2&#34;