我试图从特定行的标签文件中读取,我想逐行处理信息,以便创建包含这些行的列表。我阅读了文档,但我找不到有用的东西。
为了更清楚,我将举一个例子: 鉴于文件:
id对话
我想阅读会话行并创建如下列表:
list=['Hello,How are you', 'I am fine, thanks for asking', 'I am glad to hear that']
答案 0 :(得分:0)
这是一个oneliner的例子:
import io
file="""id conversation
1 Hello, How are you
2 I am fine, thanks for asking
3 I am glad to hear that"""
[' '.join(row.strip('\n').split(" ")[1:]) for row in io.StringIO(file).readlines() if row.strip('\n')][1:]
打印
['Hello, How are you',
'I am fine, thanks for asking',
'I am glad to hear that']
import io
file="""id conversation
1 Hello, How are you
2 I am fine, thanks for asking
3 I am glad to hear that"""
with open("test.txt", "w") as f:
f.write(file)
with open("test.txt") as f:
mylist = [' '.join(row.strip('\n').split(" ")[1:]) for row in f.readlines() if row.strip('\n')][1:]
mylist