gpt4 book ai didi

python - 将具有一个共同元素的列表列表组合在一起并保存到单独的文本文件中(python)

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:31 25 4
gpt4 key购买 nike

我有一个包含以下数据的 .txt 文件:

header1 header2 header3

173.012 -30.330 19

173.012 -30.349 19

173.012 -30.344 19

173.013 -30.345 21

173.013 -30.343 21

173.013 -30.349 21

173.014 -30.343 22

173.014 -30.325 22

173.014 -30.326 22

173.015 -30.348 24

173.016 -30.336 25

173.016 -30.318 25

173.016 -30.318 25

173.016 -30.318 25

173.016 -30.318 25

173.016 -30.318 25

173.016 -30.318 25

我想做的事情:

  1. 保存标题信息,以便我将来可以引用
  2. 将与相同 header3 值对应的每一行组合在一起,并将其保存在自己单独的 .txt 文件中。例如,预期的输出会给我一个文件,其中前三行的第 3 个元素(header3 值)为 19,然后是另一个 .txt 文件,其中应包含接下来的三行,因为它们包含 header3 值为 21 和依此类推,直到完成行数。

我的尝试:

这是我目前所拥有的:我尝试使用:

import re
def extract(oldfile,newfile,char):
f = open(oldfile, “r”)
f1 = f.readline()
for x in range(len(f1)):
if re.match(char, x):
g = open(newfile, "w")
g.write(x)

else:
print('does not work\n')

问题:它确实有效,但每次我都必须手动定义必须使用的字符“char”,它需要在正在读取的每一行中匹配。

2.

def extract(oldfile):
file = open(oldfile, "rU")
f = file.readlines()
f1 = map(str.strip,f)
f2 = [sub.split ('\t') for sub in f1]
for i in range(len(f2)):
if f2[i][2] == f2[i+1][2]:
print('works')
else:
print('no')

在这里,我的输出如下:

works
works
no
works
works
no
works
works
no
no
works
works
works
works
works
works

*(我知道这是简单打印而不是在文本文件中注销的代码,我只是想了解我的 for 循环的结构以及它是否正常工作!)

所以我的问题是:我不确定如何告诉 python group 大列表 f2 中的所有列表,它们具有共同的第三个元素,如果它们不匹配,则继续下一个.我无法解决的问题是我应该如何设计我的 for 循环,其中术语匹配的不连续性不会停止文件,并简单地继续并尝试匹配它之后的那些?

我不确定我是否解释得很好,但我的最终目标是:

我想保存单独的文本文件,这些文件只有对应于相同 header3 值的行/行。

最佳答案

import itertools

# read in the lines from the input file
with open('/path/to/input.txt') as f:
lines = f.readlines()

# write out the first line to a headers file
with open('headers', 'w') as o:
o.write(lines[0])

# group lines by the last word on each (after splitting around spaces)
for group, items in itertools.groupby(lines[1:], lambda x: x.split()[-1]):
# write out a 'group_n' file for each group (e.g. group_19, group_21, etc.)
with open('group_%s' % group, 'w') as o:
o.writelines(items)

关于python - 将具有一个共同元素的列表列表组合在一起并保存到单独的文本文件中(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com