如何将标记化的句子作为行附加到 csv
how to append tokenized sentences as row to a csv
我正在尝试对路径中的几个 .txt 文件进行句子标记化,然后将每个标记化的句子附加到一个新行,*.txt 文档 ID 为 csv。
路径中有多个*txt文件(work_dir)
在下面的示例中,第一列需要是文件名 (WLTW_5_2016_02_29),下一列是标记化的句子。这样,如果文档中有 40 个句子,我希望在第一列和第二列句子中有 40 行具有相同的文件名。我还附上了一张图片以显示 csv 输出的预期方式。
import nltk
work_dir='/content/drive/My Drive/deneme'
filename = 'WLTW_5_2016_02_29.txt'
file = open(filename, 'rt')
text = file.read()
#file.close()
# split into sentences
from nltk import sent_tokenize
sentences = sent_tokenize(text)
print(sentences)
import csv
with open('writeData.csv', mode='w') as file:
writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(("filename", "sentence"))
writer.writerow((filename, sentences))
我试过这种方法,但我无法做到。
使用上面的代码,它将所有内容写入同一行。但是,如上例所示,我想通过附加为行将它们写入同一列。
我认为我的问题出在代码的顺序上:
工作的来了,如果有人遇到同样的问题,请随时使用它:
import nltk, glob, csv
from nltk import sent_tokenize
files = glob.glob("/content/drive/My Drive/deneme/*.txt")
with open('writeData.csv', mode='w') as new_file:
writer = csv.writer(new_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for filename in files:
# Take all sentences from a given file
file = open(filename, 'rt')
text = file.read()
file.close()
sentences = sent_tokenize(text)
print(sentences)
for sentence in sentences:
writer.writerow((filename, sentence))
我正在尝试对路径中的几个 .txt 文件进行句子标记化,然后将每个标记化的句子附加到一个新行,*.txt 文档 ID 为 csv。
路径中有多个*txt文件(work_dir) 在下面的示例中,第一列需要是文件名 (WLTW_5_2016_02_29),下一列是标记化的句子。这样,如果文档中有 40 个句子,我希望在第一列和第二列句子中有 40 行具有相同的文件名。我还附上了一张图片以显示 csv 输出的预期方式。
import nltk
work_dir='/content/drive/My Drive/deneme'
filename = 'WLTW_5_2016_02_29.txt'
file = open(filename, 'rt')
text = file.read()
#file.close()
# split into sentences
from nltk import sent_tokenize
sentences = sent_tokenize(text)
print(sentences)
import csv
with open('writeData.csv', mode='w') as file:
writer = csv.writer(file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(("filename", "sentence"))
writer.writerow((filename, sentences))
我试过这种方法,但我无法做到。
使用上面的代码,它将所有内容写入同一行。但是,如上例所示,我想通过附加为行将它们写入同一列。
我认为我的问题出在代码的顺序上:
工作的来了,如果有人遇到同样的问题,请随时使用它:
import nltk, glob, csv
from nltk import sent_tokenize
files = glob.glob("/content/drive/My Drive/deneme/*.txt")
with open('writeData.csv', mode='w') as new_file:
writer = csv.writer(new_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for filename in files:
# Take all sentences from a given file
file = open(filename, 'rt')
text = file.read()
file.close()
sentences = sent_tokenize(text)
print(sentences)
for sentence in sentences:
writer.writerow((filename, sentence))