【问题标题】:How to compare contents of two large text files in Python?如何在 Python 中比较两个大文本文件的内容?
【发布时间】: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


    【解决方案1】:

    首先,您的任务是替换 test 文件中在 train 文件中看不到的单词。您的代码从未提及测试文件。你必须

    • 阅读训练文件,收集那里的单词。这基本上没问题;但是你需要.strip()你的line,否则每行的最后一个单词将以换行符结尾。此外,如果您不需要知道计数,使用set 而不是dict 会更有意义(您不需要,您只想知道它是否存在)。集合很酷,因为您不必关心元素是否已经存在;扔进去就行了。如果你绝对需要知道计数,使用collections.Counter 比自己做要容易。

    • 读取 test 文件,并写入替换文件,因为您正在替换每一行中的单词。比如:

      以 open("test", "rt") 作为阅读器: 以 open("replacement", "wt") 作为作者: 对于阅读器中的行: writer.write(replaced_line(line.strip()) + "\n")

    • 有意义,你的最后一个块没有:P 不是查看测试文件中的单词是否被看到,而是替换未看到的单词,而是迭代你在训练文件中看到的单词,并编写&lt;unk&gt; 如果你只见过他们一次。这确实有所作为,但没有达到应有的效果。

      相反,拆分您从测试文件中获得的行并迭代其单词;如果单词在可见集合中(word in seen,字面意思),则替换其内容;最后将其添加到输出句子中。您可以循环执行,但这里有一个理解:

      new_line = ' '.join(word if word in seen else '<unk>'
                          for word in line.split(' '))
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多