[英]How to separate monthly and daily filenames on python list into two separate lists?
I have a list:我有一个清单:
allFiles =['https://myurl.com/something//something_01-01-2020.csv',
'https://myurl.com/something//something_01-02-2020.csv',
'https://myurl.com/something//something_03-2020.csv'
'https://myurl.com/something//something_01-03-2020.csv',
'https://myurl.com/something//something_04-2020.csv'...]
How can I separate monthly and daily files into two separate lists?如何将每月和每天的文件分成两个单独的列表?
Desired output:期望的输出:
daily = ['https://myurl.com/something//something_01-01-2020.csv',
'https://myurl.com/something//something_01-02-2020.csv',
'https://myurl.com/something//something_01-03-2020.csv']
monthly = ['https://myurl.com/something//something_03-2020.csv',
'https://myurl.com/something//something_04-2020.csv']
I was trying the bellow but unsuccessfully:我正在尝试波纹管但没有成功:
daily = [ x for x in allFiles if "%m-%Y.csv" not in x ]
Could someone please help?有人可以帮忙吗? Thank you in advance!先感谢您!
Here is a solution making use of regex
to identify daily and monthly date pattern's,这是一个使用regex
来识别每日和每月日期模式的解决方案,
import re
daily_pattern = re.compile(r"\d{2}-\d{2}-\d{4}.csv")
monthly_pattern = re.compile(r"\d{2}-\d{4}.csv")
monthly, daily = [], []
for f in allFiles:
if daily_pattern.search(f):
daily.append(f)
elif monthly_pattern.search(f):
monthly.append(f)
else:
print('invalid pattern %s' % f)
You can split the url to get only the part you want, then count the hyphens to see the format of the date:您可以拆分 url 以仅获取您想要的部分,然后计算连字符以查看日期的格式:
monthly = []
daily = []
for url in all_files:
# splits the url string by '/', returns only the part after the last '/'
filename = url.rsplit('/', 1)[-1]
# same as before but split by '_' and getting only similar to 01-01-2020.csv
datestring = filename.rsplit('_', 1)[-1]
datestring_hyphens = datestring.count('-')
if datestring_hyphens == 1:
monthly.append(datestring)
elif date_string_hyphens == 2:
daily.append(datestring)
first create a function allowing to sort the URLs in order to classify those being days and those being months首先创建一个允许对 URL 进行排序的函数,以便对那些是天和那些是月进行分类
allFiles =['https://myurl.com/something//something_01-01-2020.csv',
'https://myurl.com/something//something_01-02-2020.csv',
'https://myurl.com/something//something_03-2020.csv'
'https://myurl.com/something//something_01-03-2020.csv',
'https://myurl.com/something//something_04-2020.csv']
def month_or_day(string):
return len(string.split('_')[1].split(".")[0].split('-'))
Then create a dataframe to apply this function to each URL然后创建一个数据框以将此函数应用于每个 URL
df=pd.DataFrame(allFiles,columns=['URL'])
df['Month_day']=0
df['intermediate'] = pd.Series(allFiles).apply(lambda x : month_or_day(x))
You get the URLS separation as follows:你得到的 URLS 分离如下:
print('Month : ',df[df['intermediate']==2]['URL'].tolist())
print('')
print('Day : ',df[df['intermediate']==3]['URL'].tolist())
Using regular expressions:使用正则表达式:
import re
daily_pattern = r"""
^ # Start of string
.+? # Match anything except newline (not greedy)
\d{2} # Two numerical values.
- # Hyphen
\d{2} # Two numerical values.
- # Hyphen
\d{4} # Four numerical values.
\.\w+ # File extension with escaped period.
$ # End of string
"""
# Compile with re.M (ignore case) and re.X (handle pattern verbosity)
p = re.compile(daily_pattern, flags=re.I | re.X)
daily = [f for f in allFiles if p.match(f)]
monthly = [f for f in allFiles if not f in daily]
EDIT: Updated to include more explanation.编辑:更新以包含更多解释。
May be like this可能是这样的
month_files = [f for f in allFiles if len(f.rpartition('_')[2].split('-'))==2]
day_files = [f for f in allFiles if len(f.rpartition('_')[2].split('-'))==3]
rpartition
will split the file on _
and give you 3 items like ['somename','_','the date/month .csv']
you can filter on the date part with split and length checking. rpartition
将在_
上拆分文件,并为您提供 3 个项目,例如['somename','_','the date/month .csv']
您可以通过拆分和长度检查过滤日期部分。
with rpartition
it'll work even if the filename has multiple _
.使用rpartition
即使文件名有多个_
它也会工作。
You can use Regex here您可以在此处使用正则表达式
Ex:前任:
import re
allFiles =['https://myurl.com/something//something_01-01-2020.csv',
'https://myurl.com/something//something_01-02-2020.csv',
'https://myurl.com/something//something_03-2020.csv',
'https://myurl.com/something//something_01-03-2020.csv',
'https://myurl.com/something//something_04-2020.csv']
daily = []
monthly = []
for i in allFiles:
if re.search(r"_(\d+\-\d+\.csv)$", i):
monthly.append(i)
else:
daily.append(i)
print(daily)
print(monthly)
Output:输出:
['https://myurl.com/something//something_01-01-2020.csv', 'https://myurl.com/something//something_01-02-2020.csv', 'https://myurl.com/something//something_01-03-2020.csv']
['https://myurl.com/something//something_03-2020.csv', 'https://myurl.com/something//something_04-2020.csv']
Assuming that there is no other "_" in the file name:假设文件名中没有其他“_”:
monthly = [file for file in allFiles if len(file.split('_')[1].split('-')) == 2]
daily = [file for file in allFiles if len(file.split('_')[1].split('-')) == 3]
Notice that you have a mistake in your example, there is a missing comma.请注意,您的示例中有一个错误,缺少逗号。
Your issue is well-suited for regular expressions.您的问题非常适合正则表达式。
import re
allFiles =['https://myurl.com/something//something_01-01-2020.csv',
'https://myurl.com/something//something_01-02-2020.csv',
'https://myurl.com/something//something_03-2020.csv',
'https://myurl.com/something//something_01-03-2020.csv',
'https://myurl.com/something//something_04-2020.csv']
dailyRegexp = re.compile(r".*\d\d-\d\d-\d\d\d\d\.csv$")
isDaily = lambda fn: dailyRegexp.match(fn)
daily = [fn for fn in allFiles if isDaily(fn)]
monthly = [fn for fn in allFiles if not isDaily(fn)]
print("Daily:", daily)
print("Monthly:", monthly)
Explanation of the regexp:正则表达式的解释:
.*
is any character ( .
), repeated arbitrary times ( *
) .*
是任意字符 ( .
),重复任意次 ( *
)\\d
is any digit \\d
是任何数字-
is just literal character -
, no special meaning -
只是字面意思-
,没有特殊含义\\.
is a dot character (escaped by backslash to prevent special meaning)是一个点字符(用反斜杠转义以防止特殊含义)csv
is literal string, no special meaning csv
是文字字符串,没有特殊含义$
is end of string $
是字符串的结尾Notice also r
before the string.还要注意字符串前的r
。 It signifies raw string that prevents Python to interpret \\
as special character.它表示防止 Python 将\\
解释为特殊字符的原始字符串。 More info:更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.