有没有更好的方法从Python中的目录列表中分割细节

2024-06-17 15:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将文件列表转换为结构化数据。 这是windows中的标准文件列表,如下所示

目前我正在使用空格将其拆分。 首先将多个空间替换为单个空间,然后在空间上拆分。但我觉得使用正则表达式和匹配/分组可以更好地做到这一点(或者假设可以更好地做到)

我当前的代码如下所示

def extract_columns_from_file_name(text, curr_dir, mappedProductNames):    

text = re.sub('\s+',' ',text)
space_location = text.find(" ")
date = text[0:space_location]
text = text[space_location+1:len(text)]

space_location = text.find(" ")
timeA = text[0:space_location]
text = text[space_location+1:len(text)]

space_location = text.find(" ")
timeB = text[0:space_location]
text = text[space_location+1:len(text)]

time = timeA + " " + timeB

space_location = text.find(" ")
size = text[0:space_location]
size = re.sub(',','',size)
text = text[space_location+1:len(text)]

我正在转换的文本如下所示

28/11/2019  05:26 PM     2,074,273,364 jdev_suite_122130_win64.exe

Tags: 文件数据textre列表sizelenwindows
3条回答

使用Pandas更好地操作数据

import pandas as pd
df = pd.read_csv(filename, sep=' ', header=None)

您可以简单地使用split,它将根据空间进行拆分,并返回一个包含所有字段的列表

fields = text.split()
print (fields)

输出将为&;你可以随心所欲地使用它

['28/11/2019', '05:26', 'PM', '2,074,273,364', 'jdev_suite_122130_win64.exe']     

您可以通过regex这样做:

import re

text = "28/11/2019  05:26 PM     2,074,273,364 jdev_suite_122130_win64.exe"

m = re.match(r'(\d+/\d+/\d+) +(\d{2}:\d{2} (?:AM|PM)) +([0-9,]+) ([\w.]+)', text)
if m:
    print(m.groups())

输出:

('28/11/2019', '05:26 PM', '2,074,273,364', 'jdev_suite_122130_win64.exe')

相关问题 更多 >