【问题标题】:How to iterate on a file in python where records are multi-line with comma separated fields and the records are delimited by an empty line?如何迭代python中的文件,其中记录是多行的,带有逗号分隔的字段,并且记录由空行分隔?
【发布时间】:2019-01-27 19:07:21
【问题描述】:

以下数据集由句子组成,其中每个单词都单独标记。我想把它分成两个变量来训练我的模型。记录由空行分隔,每条记录跨越多行,其中单词和标签以逗号分隔。

how,SW
is,SW
the,SW
weather,WTR
?,.
       # blank line
will,SW
it,SW
rain,RAIN
this,ADJ
weekend,TIME
?,.

我想处理这个输入文件以生成预期的输出,如下所示:

X 变量必须包含每条记录的所有单词作为单独的列表:

[[how, is, the, weather, ?], [will it rain this weekend, ?]]

Y 变量必须包含每条记录的标签作为单独的列表:

[[SW, SW, SW, WTR, .], [SW, SW, RAIN, ADJ, TIME, .]]

请提出建议。谢谢!

【问题讨论】:

  • 一行你只有一个词,标签对?或者可以更多?
  • 文件末尾是否也有空行?
  • 每一行只包含一对word,label。
  • 文件结尾可以是空行。无论哪种方式都可以,只要它更容易处理即可。

标签: python named-entity-extraction


【解决方案1】:

可能这样的事情会起作用:

Xs = []
Ys = []
with open('file.txt', 'r') as f:
    lines = f.readlines()
i = 0
X = []
Y = []
for line in lines:
    line = line.strip()
    if line == "":
        Xs.append(X)
        Ys.append(Y)
        X,Y = [],[]
    else:
        x,y = line.split(",")
        X.append(x)
        Y.append(y)
Xs.append(X)
Ys.append(Y)
print(Xs)
print(Ys)

#[['how', 'is', 'the', 'weather', '?'], ['will', 'it', 'rain', 'this', 'weekend', '?']]
#[['SW', 'SW', 'SW', 'WTR', '.'], ['SW', 'SW', 'RAIN', 'ADJ', 'TIME', '.']]

代码基本上是打开文件,读取所有行,并遍历这些行以检查我们是否已完成导入记录(如空行所示)并采取相应措施。 line.strip() 删除行中的所有空格,因此"\n".strip() 将输出""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多