【发布时间】:2018-04-06 04:10:39
【问题描述】:
我有一个文本文件,我想以某种格式读入列表。
当我写作时:
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]
这给出了相同的结果。再想一想,为什么它不起作用是有道理的。不过希望得到一些帮助。
【问题讨论】:
-
为什么不直接测试当前行,如果匹配则先输出一个换行符?
-
文件长什么样?
-
该文件类似于
27/08/15, 15:45 - text continue text continue text 2,但是当我读取行时我得到27/08/15, 15:45 - text\ncontinue text\ncontinue text 2@IgnacioVazquez-Abrams 没有不需要的数据。我正在使用所有东西,我只是希望它采用正确的格式 -
@sheldonzy,你试过
open('chat_history.txt', encoding='utf8', newline='')吗?
标签: python regex file split strip