我有一个文本文件,其中包含多个3行文本块,后接一个新行。我的数据如下所示:
title A - description
http://www.a.site.com/
http://a.anothersite.com/
title B - blah blah
http://www.site.b.com/
http://b.anothersite.com/
title C - yeah yeah
http://www.site.c.com/
http://anothersite.c.com/
我希望实现的输出是这样的:
title A - description | http://www.a.site.com/ | http://a.anothersite.com/
title B - blah blah | http://www.site.b.com/ | http://b.anothersite.com/
title C - yeah yeah | http://www.site.c.com/ | http://anothersite.c.com/
我一直在尝试使用python做到这一点,但我真的没有得到任何帮助。我能做到的最好的就是删除所有新行,但是在这种情况下并没有真正的帮助,因为我仍然需要在每条数据之间添加新行。有什么建议?
尝试这个:
import re
with open("file.txt", "r+") as f:
text = " | ".join(f.readlines())
text = re.sub(r"(?<!^)\n", '', text)
text = re.sub(r"\s*\|\s*\|\s*", "\n", text)
f.seek(0)
f.write(text)
输出file.txt
:
title A - description | http://www.a.site.com/ | http://a.anothersite.com/
title B - blah blah | http://www.site.b.com/ | http://b.anothersite.com/
title C - yeah yeah | http://www.site.c.com/ | http://anothersite.c.com/
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句