从Python或R中的文件名列表中提取子字符串
我的问题与以下非常相似:。我是Python新手,更喜欢Python(或R)的类似解决方案。我想查看一个目录,从每个适用的文件名中提取一个特定的子字符串,并将其输出为向量(首选)、列表或数组。例如,假设我有一个具有以下文件名的目录:从Python或R中的文件名列表中提取子字符串,python,r,bash,Python,R,Bash,我的问题与以下非常相似:。我是Python新手,更喜欢Python(或R)的类似解决方案。我想查看一个目录,从每个适用的文件名中提取一个特定的子字符串,并将其输出为向量(首选)、列表或数组。例如,假设我有一个具有以下文件名的目录: data_ABC_48P.txt data_DEF_48P.txt data_GHI_48P.txt other_96.txt another_98.txt 我想引用目录并提取以下内容作为字符向量(用于R)或列表: 我尝试了以下方法: from os import
data_ABC_48P.txt
data_DEF_48P.txt
data_GHI_48P.txt
other_96.txt
another_98.txt
我想引用目录并提取以下内容作为字符向量(用于R)或列表:
我尝试了以下方法:
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
文件
属于类型
列表
In [10]: type(files)
Out[10]: list
尽管我最终希望将此字符向量作为R代码的输入,但我们正在尝试将所有“脚本”转换为Python,并仅将R用于数据分析,因此Python解决方案将是非常好的。我也在使用Ubuntu,所以cmd行或bash脚本解决方案也可以。提前谢谢
re.search
需要字符串而不是列表
使用
使用列表理解,例如
[re.search(r'data_(.+?)_48P', i).group(1) for i in files if re.search(r'data_.+?_48P', i)]
您需要迭代列表内容以获取所需的子字符串。re.search()
不要接受列表作为参数您需要使用循环并将每个必须为字符串的元素传递给函数,您可以使用for-give-your-expected string,然后作为re的结果。search
是一个生成器,您需要group
来获取字符串
>>> for i in files :
... try :
... print re.search(r'(?<=data_).*(?=_48P)', i).group(0)
... except AttributeError:
... pass
...
ABC
DEF
GHI
文件中的i的>>:
... 尝试:
... 打印检索(r’(?)?
输出:
['ABC', 'DEF', 'GHI']
在R中:
list.files(“~/desktop/test”)
#[1]“另一个_98.txt”“数据_ABC_48P.txt”“数据_DEF_48P.txt”“数据_GHI_48P.txt”“其他_96.txt”
gsub(“”,“”,未列出(regmatches(l
>>> for i in files :
... try :
... print re.search(r'(?<=data_).*(?=_48P)', i).group(0)
... except AttributeError:
... pass
...
ABC
DEF
GHI
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']
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"