预期的投入和产出:
a -> a
a.txt -> a
archive.tar.gz -> archive
directory/file -> file
d.x.y.z/f.a.b.c -> f
logs/date.log.txt -> date # Mine!
Run Code Online (Sandbox Code Playgroud)
这是我对我感到肮脏的实现:
>>> from pathlib import Path
>>> example_path = Path("August 08 2015, 01'37'30.log.txt")
>>> example_path.stem
"August 08 2015, 01'37'30.log"
>>> example_path.suffixes
['.log', '.txt']
>>> suffixes_length = sum(map(len, example_path.suffixes))
>>> true_stem = example_path.name[:-suffixes_length]
>>> true_stem
"August 08 2015, 01'37'30"
Run Code Online (Sandbox Code Playgroud)
因为它在Path
没有后缀的情况下中断:
>>> ns_path = Path("no_suffix")
>>> sl = sum(map(len, ns_path.suffixes))
>>> ns_path.name[:-sl]
''
Run Code Online (Sandbox Code Playgroud)
所以我需要先检查Path
后缀是否有后缀:
>>> def get_true_stem(path: …
Run Code Online (Sandbox Code Playgroud)