我需要從文件名,如只提取號碼:如何在Python中從文件名中提取數字?
GapPoints1.shp
GapPoints23.shp
GapPoints109.shp
我怎樣才能從這些文件中提取只是數字使用Python?我需要將其合併到for
循環中。
我需要從文件名,如只提取號碼:如何在Python中從文件名中提取數字?
GapPoints1.shp
GapPoints23.shp
GapPoints109.shp
我怎樣才能從這些文件中提取只是數字使用Python?我需要將其合併到for
循環中。
你可以使用正則表達式:
regex = re.compile(r'\d+')
然後得到匹配的字符串:
regex.findall(filename)
這將返回包含數字的字符串列表。如果你真的想整數,你可以使用int
:
[int(x) for x in regex.findall(filename)]
如果只有1中每個文件名數量,你可以使用regex.search(filename).group(0)
(如果你一定認爲它會產生一個匹配)。如果找不到匹配項,上面的行會產生一個AttributeError,說NoneType
沒有屬性group
。
如果只有一個數字:
filter(lambda x: x.isdigit(), filename)
我建議're'模塊。 – squiguy