【发布时间】:2021-09-27 11:10:11
【问题描述】:
我有两种文件,xml files 和 txt files。这些文件的名称中有一个日期。如果xml file 的日期与txt file 的日期匹配,我想打开txt file 进行一些处理并将输出写入列表。之后我想更改xml file。多个xml files 可以具有相同的日期,但txt file 是唯一的,因此这意味着可以将超过1 个xml file 与txt file. 链接
现在我有一个问题。我的to_csv 列表包含 20200907 和 20201025 的数据。我不希望它那样工作。我希望我的to_csv 列表一次只做一个文件(因此是一个日期)。
output_xml = r"c:\desktop\energy\XML_Output"
output_txt = r"c:\desktop\energy\TXT_Output"
xml_name = os.listdir(output_xml )
txt_name = os.listdir(output_txt)
txt_name = [x.replace('-', '') for x in txt_name] #remove the - in the filenames
# Extract the date from the xml and txt files.
xml_dates = []
for file in xml_name:
find = re.search("_(.\d+)-", file).group(1)
xml_dates.append(find)
txt_dates = []
for file in txt_name:
find = re.search("MM(.+?)AB", file).group(1)
txt_dates.append(find)
#THIS IS SOME REPRODUCABLE OUTPUT FROM WHAT IS RECEIVED FROM ABOVE SNIPPET.
xml_dates = ['20200907', '20200908', '20201025', '20201025', '20201025', '20201025']
txt_dates = ['20200907', '20201025']
to_csv = []
for date_xml in xml_dates:
for date_txt in txt_dates:
if date_xml == date_txt:
match_txt = [s for s in txt_name if date_txt in s] # matching txt file
match_xml = [s for s in xml_name if date_xml in s] # matching xml file
match_txt_temp = match_txt[0]
match_txt_score = [match_txt_temp[:6]+'-'+match_txt_temp[6:8]+'-'+match_txt_temp[8:10]+'-'+match_txt_temp[10:12]+match_txt_temp[12:]]
with open(output_txt + "/" + match_txt_score[0], "r") as outer:
reader = csv.reader(outer, delimiter="\t")
for row in reader:
read = [row for row in reader if row]
for row in read:
energy_level = row[20]
if energy_level > 250:
to_csv.append(row)
print(to_csv)
当前输出:
[['1', '2', '3', '20200907', '4', '5'],
['1', '2', '3', '20200907', '4', '5'],
['1', '2', '3', '20200907', '4', '5'],
['1', '2', '3', '20201025, '4', '5'],
['1', '2', '3', '20201025, '4', '5']]
期望的输出:
[[['1', '2', '3', '20200907', '4', '5'],
['1', '2', '3', '20200907', '4', '5'],
['1', '2', '3', '20200907', '4', '5']],
['1', '2', '3', '20201025, '4', '5'],
['1', '2', '3', '20201025, '4', '5']]
【问题讨论】:
-
@Iguananaut 不,它们不一样。在所需的输出中,我在最后一个按日期分隔的列表中有一个列表。在当前的输出中,它的全部在一个
-
是的,我看到了。
-
@Iguananaut 如果您有其他想法来解决这个问题,请告诉我,我不喜欢这样的嵌套列表,但找不到任何其他解决方案
-
根据您提供的代码,您可以通过摆脱双 for 循环和 if 语句来大大简化此操作。如果您有两个列表
xml_dates和txt_dates,您可以通过取两个matching_dates = set(xml_dates).intersection(txt_dates)的集合交集然后循环matching_dates来处理匹配的日期。我认为您还有其他一些错误,例如在reader上进行双循环(在reader上的for 循环中有一些[row for row in reader if row],这是没有意义的)。 -
@Iguananaut 你能在答案中展示它吗?这也让我有机会接受你的回答。