簡體   English   中英

從Python中的文件名中提取子字符串?

[英]Extract substring from filename in Python?

我有一個充滿文件的目錄,這些文件的日期字符串是文件名的一部分:

file_type_1_20140722_foo.txt
file_type_two_20140723_bar.txt
filetypethree20140724qux.txt

我需要從文件名中獲取這些日期字符串,並將它們保存在數組中:

['20140722', '20140723', '20140724']

但是它們可以出現在文件名的不同位置,所以我不能只使用子字符串表示法並直接提取它。 過去,我在Bash中完成類似操作的方式如下:

date=$(echo $file | egrep -o '[[:digit:]]{8}' | head -n1)

但是我不能為此使用Bash,因為它在數學上很爛 (我需要能夠加減浮點數)。 我已經嘗試過glob.glob()re.match() ,但是都返回空集:

>>> dates = [file for file in sorted(os.listdir('.')) if re.match("[0-9]{8}", file)]
>>> print dates
>>> []

我知道問題在於它正在尋找八位數字長的完整文件名,但是我不知道如何使它查找子字符串。 有任何想法嗎?

>>> import re
>>> import os
>>> [date for file in os.listdir('.') for date in re.findall("(\d{8})", file)]
['20140722', '20140723']

請注意,如果文件名具有9位數字的子字符串,則僅前8位數字將被匹配。 如果文件名包含16位數字的子字符串,將有2個不重疊的匹配項。

re.match從字符串開頭開始匹配。 re.search在任何地方匹配模式。 或者,您可以嘗試以下操作:

extract_dates = re.compile("[0-9]{8}").findall
dates = [dates[0] for dates in sorted(
    extract_dates(filename) for filename in os.listdir('.')) if dates]

您的正則表達式看起來不錯,但是您應該使用re.search而不是re.match,以便它將在字符串中的任何位置搜索該表達式:

import re
r = re.compile("[0-9]{8}")
m = r.search(filename)
if m:
    print m.group(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM