从Python或R中的文件名列表中提取子字符串

时间:2014-12-05 17:13:09

标签: python r bash

我的问题非常类似于以下内容:How to get a Substring from list of file names。我是Python的新手,并且更喜欢Python(或R)的类似解决方案。我想查看一个目录并从每个适用的文件名中提取一个特定的子字符串,并将其输出为向量(首选),列表或数组。例如,假设我的目录包含以下文件名:

data_ABC_48P.txt
data_DEF_48P.txt
data_GHI_48P.txt
other_96.txt
another_98.txt

我想引用该目录并将以下内容提取为字符向量(用于R)或列表:

"ABC", "DEF", "GHI"

我尝试了以下内容:

from os import listdir
from os.path import isfile, join
files = [ f for f in listdir(path) if isfile(join(path,f)) ]
import re
m = re.search('data_(.+?)_48P', files)

但是我收到以下错误:

TypeError: expected string or buffer

files属于type list

In [10]: type(files)
Out[10]: list

尽管我最终希望这个角色向量作为R代码的输入,但我们正试图过渡所有的脚本和#34;对Python而言,只使用R进行数据分析,因此Python解决方案会很棒。我也使用Ubuntu,因此cmd行或bash脚本解决方案也可以正常工作。提前致谢!

5 个答案:

答案 0 :(得分:2)

使用列表理解,例如,

[re.search(r'data_(.+?)_48P', i).group(1) for i in files if re.search(r'data_.+?_48P', i)]

您需要迭代列表内容以获取所需的子字符串。

答案 1 :(得分:0)

re.search要求字符串不是列表。

使用

m=[]
for line in files:
   import re
   m.append(re.search('data_(.+?)_48P', line).group(1))

答案 2 :(得分:0)

re.search()不要接受列表作为参数,你需要使用循环并将必须为字符串的每个元素传递给函数,你可以使用positive look-around给出你期望的字符串然后作为结果re.search是您需要group来获取字符串

的生成器
>>> for i in files :
...   try :
...    print re.search(r'(?<=data_).*(?=_48P)', i).group(0)
...   except AttributeError:
...    pass
... 
ABC
DEF
GHI

答案 3 :(得分:0)

from os import listdir
from os.path import isfile, join
import re
strings = []
for f in listdir(path):
    if isfile(join(path,f)):
        m = re.search('data_(.+?)_48P', f)
        if m:
            strings.append(m.group(1))

print strings

输出:

['ABC', 'DEF', 'GHI']

答案 4 :(得分:0)

在R:

list.files('~/desktop/test')
# [1] "another_98.txt"   "data_ABC_48P.txt" "data_DEF_48P.txt" "data_GHI_48P.txt" "other_96.txt"

gsub('_', '', unlist(regmatches(l <- list.files('~/desktop/test'),
                                gregexpr('_(\\w+?)_', l, perl = TRUE))))
# [1] "ABC" "DEF" "GHI"
另一种方式:

l <- list.files('~/desktop/test', pattern = '_(\\w+?)_')

sapply(strsplit(l, '[_]'), '[[', 2)
# [1] "ABC" "DEF" "GHI"