简体   繁体   English

如何在 re.findall 中使用变量?

[英]How to use variables in re.findall?

I'm extremely new to Python, so I'm sorry if my question is rather stupid.我对 Python 非常陌生,如果我的问题很愚蠢,我很抱歉。 I have a bunch of long strings in one list and shortened parts of it in another list我在一个列表中有一堆长字符串,在另一个列表中缩短了它的一部分

Like:像:

Long string is D:\\Python\\Songs\\testsong.mp3 and short string is \\testsong.mp3长串是 D:\\Python\\Songs\\testsong.mp3 短串是 \\testsong.mp3

And I want to get a list containing 'Songs' (basically the name of the folder containing the mp3) but I have multiple folders and multiple songs so I'm trying to use re.findall but it only accepts defined patterns and my patterns change due to different songs names.我想获得一个包含“歌曲”的列表(基本上是包含 mp3 的文件夹的名称)但我有多个文件夹和多首歌曲所以我尝试使用 re.findall 但它只接受定义的模式并且我的模式发生变化因为歌名不同。

from pathlib import Path

directories = [
    "D:/Python/Songs/testsong.mp3",
    "C:/users/xyz/desktop/anothersong.mp3"
]

song_folder_names = set(Path(directory).parts[-2] for directory in directories)
print(song_folder_names)

Output: Output:

{'desktop', 'Songs'}
>>> 

Notice, that the order of the folder names is not preserved - because I'm using a set .请注意,文件夹名称的顺序未保留 - 因为我使用的是set

I'm extremely new to Python, so I'm sorry if my question is rather stupid.我对 Python 非常陌生,所以如果我的问题相当愚蠢,我很抱歉。 I have a bunch of long strings in one list and shortened parts of it in another list我在一个列表中有一堆长字符串,并在另一个列表中缩短了部分

Like:喜欢:

Long string is D:\\Python\\Songs\\testsong.mp3 and short string is \\testsong.mp3长字符串是 D:\\Python\\Songs\\testsong.mp3 短字符串是 \\testsong.mp3

And I want to get a list containing 'Songs' (basically the name of the folder containing the mp3) but I have multiple folders and multiple songs so I'm trying to use re.findall but it only accepts defined patterns and my patterns change due to different songs names.我想获得一个包含“歌曲”的列表(基本上是包含 mp3 的文件夹的名称),但我有多个文件夹和多首歌曲,所以我尝试使用 re.findall 但它只接受定义的模式并且我的模式会改变因为歌名不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM