如何为句子创建增量id?

2024-03-29 14:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的任务是一个自然语言处理任务,我必须分析一个句子语料库。句子中的每个词都是一行,这行上的每个词都要经过分析。你知道吗

句子用空行隔开。我想给每个句子一个ID,以便能够恢复另一个表中其他字段中的其他信息。预期结果是:

1 the
1 cat
1 is
1 black

2 the
2 moon
2 is
2 full

以此类推,每个单词都是一行新词。我想我应该用Python来做,但是我很困惑。你知道吗


Tags: the信息idis单词fullcat句子
1条回答
网友
1楼 · 发布于 2024-03-29 14:21:14

像这样的事情应该可以做到:

count = 1
input_file = open('input.txt', 'r')
output_file = open('results.txt', 'w')
for line in input_file:
    new_line = str(count) + ' '  + line.lstrip().replace(' ', ' ' + str(count) + ' ')
    count = count + 1
    print new_line
    output_file.write(new_line)

input_file.close()
output_file.close()

相关问题 更多 >