【问题标题】:How to compare two large text files in Python?如何在 Python 中比较两个大文本文件?
【发布时间】:2019-10-01 14:42:47
【问题描述】:

数据集:我有两个不同的文本数据集(用于训练和测试的大型文本文件,每个包含 30,000 个句子)。部分数据如下: " 富尔顿县大陪审团周五表示,对亚特兰大最近初选的调查“没有证据”表明发生了任何违规行为。 "

问题:如何在 Python 中将训练中未出现的测试数据中的每个单词替换为单词“unk”?

我的解决方案:我是否应该使用“嵌套 for 循环”将训练数据的所有单词与测试数据的所有单词进行比较,以及使用“if 语句”来判断是否存在测试数据中的单词不在训练数据中,然后替换为“unk”?

#open text file and assign it to varaible with the name "readfile"
readfile1= open('train.txt','r')
#create the new empty text file with the new name and then assign it to variable 
# with the name "writefile". now this file is ready for writing in that
writefile=open('test.txt','w')
for word1 in readfile1:
    for word2 in readfile2:
        if (word1!=word2):
            word2='unk'
writefile.close()

【问题讨论】:

  • 您项目中的一些示例代码非常适合包含在您的问题中。
  • “我应该使用“嵌套 for 循环”吗?可能不会。忽略这种东西可能有一些库的可能性,看看sets(特别是set difference)和re.sub
  • 欢迎来到 SO;请不要使用ml 标记机器学习问题(请参阅tag description);另外,问题实际上与machine-learning 无关(两个标签都被删除并替换为texttext-processing

标签: python machine-learning text nlp text-processing


【解决方案1】:

请尝试以下方法:

  1. 将您的训练集转换为字典,其中工作为键,计数为值。例如:
    {"Hello":1,
    "World":2}
  1. 对于测试集中的每个单词,尝试访问 dict 中不存在的单词,然后替换为“unk”。
     def fun(testset):
            newtestset= testset
            for word in testset:
             try:
              Count = word_dict['Hello']
             except:
              newtestset.replace(word,'unk')
            return newtestset
  1. 为所有的txt文件生成dict:
def freq(str): 
    
    out_dict = {}
    # break the string into list of words 
    str_list = str.split() 
  
    # gives set of unique words 
    unique_words = set(str_list) 

    for word in unique_words:
        out_dict[word] = str_list.count(word)
    return out_dict

【讨论】:

  • 非常感谢,普拉文。你能告诉我如何制作包含每个单词及其计数的字典集吗? (正如我所说,我的每个训练和测试数据集都是一个大文本文件。一个包含 20,000 多个句子的文本文件)。
  • 修改了答案来处理这个问题。
猜你喜欢
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多