如何在 for 循环中(在 python 中)从 word 文档的文件名中提取特定名称?

How do I extract a specific name from the filename of word document in a for loop (in python)?

下面是循环所有word文档文件的for循环。正如您在下面看到的,我已经打印了文件名以查看它的输出。

for filename in os.listdir(root_dir):
            source_directory = root_dir + '/' + filename
            # The output of filename is shown in the next section.
           -> print(filename)
            arr = mynotes_extractor.get_mynotes(source_directory)
            list2str = str(arr)
            c = cleanString(newstring=list2str)
            new_arr = []
            new_arr += [c]
            text_file = open(output, 'a', encoding='utf-8')
            for item in new_arr:
                text_file.write("%s\n" % item)

下面是打印文件名后的输出:

12345_Cat_A_My Notes.docx
6789_Cat_B_My Notes.docx
54321_Cat_A_My Notes.docx
12234_Cat_C_My Notes.docx
86075_Cat_D_My Notes.docx
34324_Cat_E_My Notes.docx

我想只提取特定名称,如上所示,在for循环内的word文档的所有文件名中为"My Notes"。

For instance: 
         Before filename of word document extraction: 34324_Cat_E_My Notes.docx
         After filename of word document extraction: My Notes 

一行写的很整洁,但当您开始时可能会感到困惑。

filename.split('.')[0].split('_')[-1]

输出:'My Notes'

详细解释如下:

filename = '12345_Cat_A_My Notes.docx'

.split('.') 在每个句点拆分字符串

>>>['12345_Cat_A_My Notes', 'docx']

[0] 获取列表的第一个元素

>>>'12345_Cat_A_My Notes'

.split('_') 在每个下划线处拆分此字符串返回

>>>['12345', 'Cat', 'A', 'My Notes']

[-1] 最后,返回列表中的最后一项

>>>'My Notes'