【发布时间】:2020-01-31 08:04:58
【问题描述】:
数据集:两个大型文本文件,用于训练和测试它们的所有单词是否都已标记化。部分数据如下:“富尔顿县大陪审团周五表示,对亚特兰大最近初选的调查‘没有证据’表明发生了任何违规行为。”
问题:如何在 Python 中将训练中未出现的测试数据中的每个单词替换为单词“unk”?
到目前为止,我通过以下代码制作了字典来统计文件中每个单词的频率:
#open text file and assign it to varible with the name "readfile"
readfile= open('C:/Users/amtol/Desktop/NLP/Homework_1/brown-train.txt','r')
writefile=open('C:/Users/amtol/Desktop/NLP/Homework_1/brown-trainReplaced.txt','w')
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in readfile:
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
#replace all words occurring in the training data once with the token<unk>.
for key in list(d.keys()):
line= d[key]
if (line==1):
line="<unk>"
writefile.write(str(d))
else:
writefile.write(str(d))
#close the file that we have created and we wrote the new data in that
writefile.close()
老实说,上面的代码不适用于我想将结果写入新文本文件的 writefile.write(str(d)),但是通过 print(key, ":", line) 它可以工作并显示每个单词的频率,但在不创建新文件的控制台中。如果您也知道原因,请告诉我。
【问题讨论】:
标签: python machine-learning text nlp