我有一个文本文件,格式如下。我们有多个 "上下文 "部分,文本由多行和主题(一行主题)组成。然后有多个关于上下文段的不同id的问题。我想把上下文存储在一个列表中。其中每个上下文是列表中的一个元素。我的方法是取所有以 "context "开头的行与以 "topic "开头的行之间的行。然而,一旦我设置了条件,即我想要上下文和主题之间的行,我就不能将不同的上下文加入到同一个字符串中。下面是我的代码。
context :
|
topic:
|
question:
answer:
id:
|
question:
answer:
id:
|
context:
|
topic:
|
question:
answer:
id:
.
.
.
context = []
f = open("example.txt","r")
context_line = True
for line in f:
if not line.strip():
continue
str1 = ""
if line.startswith("context"):
context_line = True
elif line.startswith("topic"):
context_line = False
if context_line:
# Here how can I join the lines?
str1 += line.rstrip("\n").lstrip("\ufeff").strip("|")
context.append(str1)
你可以跟踪上下文中的所有行,并在主题部分开始时加入它们。
context = []
f = open("example.txt","r")
context_line = True
for line in f:
if not line.strip():
continue
if line.startswith("context"):
context_line = True
str1 = []
elif line.startswith("topic"):
lines = ' '.join(str1) # here you can choose how to join the lines
context.append(lines)
context_line = False
if context_line:
str1.append(line.rstrip("\n").lstrip("\ufeff").strip("|"))
顺便说一句,请注意这个方法不会检查输入文件的格式是否正确。特别是,如果一个 context
节后没有紧接着的是 topic
节,将无法正常工作。