0

我想提取由常量前缀和“.csv”分隔的文件名的最后一部分

文件名可能如下所示:

constant_prefix_我的文件名.csv

或者

constant_prefix_ myfilename .csv

我想将粗体标记的值提取到变量中。

请指教。

4

3 回答 3

4

脚本:

import re

name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'

def get_name(string):
    return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]

演示:

print get_name(name1)
print get_name(name2)

输出:

my file name
myfilename

或者你可以这样做:

names = [get_name(n) for n in [name1, name2]]
print names

输出:

['my file name', 'myfilename']
于 2013-06-17T21:18:23.277 回答
1

使用str.splitos.path.splitext

>>> import os
>>> prefix = 'constant_prefix'

# if your prefix includes the trailing `_` then don't use `_` in `str.split`
# i.e just use this : `strs.split(prefix)[-1]`

>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'myfilename'

>>> strs = "constant_prefix_my file name.csv"
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'my file name'
于 2013-06-17T21:14:18.367 回答
0
name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'

constant_prefix = 'constant_prefix_'

name1 = name1[len(constant_prefix):-4] # 'my file name'
name2 = name2[len(constant_prefix):-4] # 'myfilename'
于 2013-06-17T21:42:32.197 回答