gpt4 book ai didi

python - 如何清理 python 中的文本文件?

转载 作者:行者123 更新时间:2023-11-28 23:05:41 25 4
gpt4 key购买 nike

我的文件中有如下所示的文本:

text1 5,000 6,000
text2 2,000 3,000
text3
5,000 3,000
text4 1,000 2000
text5
7,000 1,000
text6 2,000 1,000

有没有办法在 Python 中清理它,以便如果文本行后缺少数字,则后续行中的数字可以放在上面的行中:

text1 5,000 6,000
text2 2,000 3,000
text3 5,000 3,000
text4 1,000 2000
text5 7,000 1,000
text6 2,000 1,000

谢谢!

最佳答案

假设每行恰好有三个“单词”,您可以使用

tokens = (x for line in open("file") for x in line.split())
for t in zip(tokens, tokens, tokens):
print str.join(" ", t)

编辑:由于上述先决条件显然不成立,这里是一个实际查看数据的实现:

from itertools import groupby
tokens = (x for line in open("file") for x in line.split())
for key, it in groupby(tokens, lambda x: x[0].isdigit()):
if key:
print str.join(" ", it)
else:
print str.join("\n", it),

关于python - 如何清理 python 中的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5794498/

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