gpt4 book ai didi

Python通过正则表达式从文件中读取行

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

我有一个文本文件,我想以某种格式读入列表。

当我写作时:

with open('chat_history.txt', encoding='utf8') as f:
mylist = [line.rstrip('\n') for line in f]

我得到:

27/08/15, 15:45 - text
continue text
continue text 2
27/08/15, 16:10 - new text
new text 2
new text 3
27/08/15, 19:55 - more text

我想得到:

27/08/15, 15:45 - text continue text continue text 2
27/08/15, 16:10 - new text new text 2 new text 3
27/08/15, 19:55 - more text

我只想在格式为 \nDD/MM/YY, HH:MM - 时拆分不幸的是,我不是正则表达式专家。我试过:

with open('chat_history.txt', encoding='utf8') as f:
mylist = [line.rstrip('\n'r'[\d\d/\d\d/\d\d - ]') for line in f]

这给出了相同的结果。再想一想,为什么它不起作用是有道理的。不过会喜欢一些帮助。

最佳答案

with open('chat_history.txt', encoding='utf8') as f:
l = [line.rstrip('\n').replace('\n', ' ') for line in f]

print(l)

关于Python通过正则表达式从文件中读取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46926163/

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