新来的。
我刚刚使用Python/coding已经有几天了,但是我想创建一个脚本来获取与某个模式对应的部分文件名,并将其输出到一个文本文件。
在我的例子中,假设我有四个这样的pdf文件:
aaa_ID_8423.pdf
bbbb_ID_8852.pdf
ccccc_ID_7413.pdf
dddddd_ID_4421.pdf
(Note that they are of variable length.)
我希望脚本遍历这些文件名,在“ID”后面和文件扩展名之前获取字符串。
你能告诉我哪些Python模块和指南可以帮助我吗?
Tags:
如果数字是可变长度的,则需要regex模块“re”
Regex通常用于匹配变量字符串。我刚写的regex说:
查找下划线(“\u”),后跟可变位数(“[0-9]+”),后跟字符串中的最后一个句点(“\.[^.]+$”)
这里还有另一种选择,使用
re.split()
,这可能更接近于您正试图做的事情的精神(尽管使用re.match()
和re.search()
等解决方案同样有效、有用和有指导意义):下面是一个使用re模块的简单解决方案,如其他答案中所述。
下面应该是你的输出。你应该能够适应其他模式。
祝你好运!
相关问题 更多 >
编程相关推荐