下面是循环所有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文档文件名中提取特定名称,即“我的笔记”,如上所示。
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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句