Python - 在文件名中匹配整数?

时间:2018-02-14 20:04:47

标签: python regex pandas

我正在创建一个数据文件,其第一列('id')中包含一个包含名称和编号的标识符(即name22,name43,name185)。我正在尝试获取标识符中的数字(来自数据文件)并将其与当前目录上方目录中的文件名中的数字相匹配 - 这些文件具有不同的名称但相同的相应数字(即old22, old43,old185)。

如何将数据文件“id”列中的数字与文件名中的数字相匹配?我写了下面的脚本,但我没有得到任何输出/错误。

import os
import fnmatch
import pandas as pd

os.system('grep id *log > data.txt')
df = pd.read_table("data.txt", delim_whitespace=True, header = None)
df.columns = ['id','anum','aname','iso']
num = df.id.str.extract('(\d+)')
regex = r'\d+'

for filename in os.listdir('../'):
    if fnmatch.fnmatch(regex,'*.txt'):
         f = open(filename,"r"):
         ...do more things....

2 个答案:

答案 0 :(得分:2)

  

此模块提供对Unix shell样式通配符的支持,这些通配符与正则表达式(在re模块中记录)不同。 shell样式通配符中使用的特殊字符是:

var apple = {
  type: "macintosh",
  color: "red",
  getInfo () {
    return this.color + ' ' + this.type + ' apple';
  }
}

fnmatch docs

这意味着你不能使用完整的正则表达式来查找文件名,只能使用shell通配符。我建议将Pattern Meaning * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq 与id一起使用,例如*

*123.txt

您也可以使用# assuminng you have id variable for filename in os.listdir('.'): if fnmatch.fnmatch(filename, '*{0}.txt'.format(id)): f = open(filename,"r") #... 功能,因为上述解决方案不是最有效的。

答案 1 :(得分:1)

如果您的id列是这样的:

f_s = pd.Series(['name22', 'name43', 'name185'])

os.listdir('../')是这样的:

others = ['old22.txt', 'old43.txt', 'old185.txt', 'mold43.png']

您可以在id

中创建一组数字
id_nbrs = set(f_s.str.extract(r'(\d+)'))

然后使用函数过滤所需的文件:

digits = re.compile(r'(\d+)$')
def f(s):
    name, ext = s.split('.')
    nbr = digits.search(name).group()
    #print(name, ext, nbr)
    return nbr in id_nbrs and ext == 'txt'

for thing in filter(f, others):
    print(thing)

>>>
old22.txt
old43.txt
old185.txt
>>>