使用NLTK将句子从.txt文件拆分为.csv文件

t3psigkw  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(171)

我在一个.txt文件中有一个报纸文章语料库,我试图将其中的句子拆分为一个.csv文件,以便为每个句子添加注解。
我被告知使用NLTK来实现这个目的,我发现了下面的句子分割代码:

import nltk

from nltk.tokenize import sent_tokenize

sent_tokenize("Here is my first sentence. And that's a second one.")

不过,我想知道:
1.如何使用.txt文件作为标记器的输入(这样就不必复制和粘贴所有内容),以及
1.如何输出一个.csv文件,而不仅仅是在我的终端上打印句子呢?

tkqqtvp1

tkqqtvp11#

阅读.txt文件并标记其语句

假设.txt文件与Python脚本位于同一个文件夹中,您可以读取.txt文件并使用NLTK对句子进行标记,如下所示:

from nltk import sent_tokenize

with open("myfile.txt") as file:
    textFile = file.read()

tokenTextList = sent_tokenize(textFile)
print(tokenTextList)
# Output: ['Here is my first sentence.', "And that's a second one."]

将句子标记列表写入.csv文件

.csv文件有很多种选择,选择哪个更方便(例如,如果你已经加载了pandas,使用pandas选项)。
要使用pandas模块写入.csv文件:

import pandas as pd

df = pd.DataFrame(tokenTextList)
df.to_csv("myCSVfile.csv", index=False, header=False)

要使用numpy模块写入.csv文件:

import numpy as np

np.savetxt("myCSVfile.csv", tokenTextList, delimiter=",", fmt="%s")

要使用csv模块写入.csv文件:

import csv

with open('myCSVfile.csv', 'w', newline='') as file:
    write = csv.writer(file, lineterminator='\n')
    # write.writerows([tokenTextList])
    write.writerows([[token] for token in tokenTextList]) # For pandas style output

相关问题