2017-09-15 32 views
-1

我有一个文件路径保存为filepath的形式/home/user/filename。什么样的文件名可能是一些例子:从文件路径提取和修改子字符串

'1990MAlogfile' 
'Tantrologfile' 
'2003RF_2004logfile' 

我需要写一些东西,变成了filepath逼到文件名的一部分(但我没有刚才保存的任何文件名尚未)。例如:

/home/user/1990MAlogfile变得'1990 MA'/home/user/Tantrologfile变得'Tantro',或/home/user/2003RF_2004logfile变得'2003 RF'

所以我需要在最后一个斜线后面和下划线之前(如果不存在的话,在'logfile'之前),然后我需要在最后一个数字和第一个字母之间插入一个空格数字存在。然后我想将结果保存为objkey。任何想法如何我可以做到这一点?我想我可以使用正则表达式,但不知道我会如何处理在这些情况下插入空间。

+0

到目前为止已经尝试过了什么?请发布您的代码。 – James

回答

0

代码
def get_filename(filepath): 

    import re 

    temp = os.path.basename(example)[:-7].split('_')[0] 

    a = re.findall('^[0-9]*', temp)[0] 

    b = temp[len(a):] 

    return ' '.join([a, b]) 


example = '/home/user/2003RF_2004logfile' 

objkey = get_filename(example) 

说明

进口正则表达式包

import re 

例如文件路径

example = '/home/user/2003RF_2004logfile' 

/home/user/2003RF_2004logfile 

得到的文件名和后删除一切_

temp = example.split('/')[-1].split('_')[0] 

2003RF 

获得开始部分(分裂,如果在开始数)

a = re.findall('^[0-9]*', temp)[0] 

2003 

得到的端部

b = temp[len(a):] 

RF 

结合开始和结束部分

return ' '.join([a, b]) 

2003 RF 
0
import os, re, string 
mystr = 'home/user/2003RF_2004logfile' 
def format_str(str): 
    end = os.path.split(mystr)[-1] 
    m1 = re.match('(.+)logfile', end) 
    try: 
     this = m1.group(1) 
     this = this.split('_')[0] 
    except AttributeError: 
     return None 
    m2 = re.match('(.+[0-9])(.+)', this) 
    try: 
     return " ".join([m2.group(1), m2.group(2)]) 
    except AttributeError: 
     return this 
相关问题