首页 > 解决方案 > 使用字典对语料库进行规范化

问题描述

我想使用字典对语料库进行词汇规范化。语料库有八千行,字典有数千个词对(非标准:标准)。

我采用了这里讨论的方法。代码如下所示:

with open("corpus.txt", 'r', encoding='utf8') as main:
    words = main.read().split()

lexnorm = {'nonstandard1': 'standard1', 'nonstandard2': 'standard2', 'nonstandard3': 'standard3', and so on}

for x in lexnorm:
    for y in words:
        if lexnorm[x][0] == y:
            y == x[1]

text = ' '.join(lexnorm.get(y, y) for y in words)

print(text)

上面的代码运行良好,但我遇到了一个问题,因为字典中有数千个单词对。是否可以通过文本文件表示字典?

最后一个问题,代码的输出文件只有一行。如果它具有与原始语料库相同的行数,那就太好了。

任何人都可以帮助我吗?我会很感激的。

标签: pythondictionarynormalizationcorpus

解决方案


将字典输出为文本文件的一种方法是作为JSON字符串:

import json

lexnorm = {'nonstandard1': 'standard1', 'nonstandard2': 'standard2', 'nonstandard3': 'standard3'} # etc.

with open('lexnorm.txt', 'w') as f:
    json.dump(lexnorm, f)

请参阅我对您原件的评论。我只是在猜测您要做什么:

import json, re

with open('lexnorm.txt') as f:
    lexnorm = json.load(f) # read back lexnorm dictionary

with open("corpus.txt", 'r', encoding='utf8') as main, open('new_corpus.txt', 'w') as new_main:
    for line in main:
        words = re.split(r'[^a-zA-z]+', line)
        for word in words:
            if word in lexnorm:
                line = line.replace(word, lexnorm[word])
        new_main.write(line)

corpus.txt上面的程序逐行读取文件并尝试智能地将行拆分为单词。在单个空间上拆分是不够的。考虑以下句子:

'"The fox\'s foot grazed the sleeping dog, waking it."'

对单个空间的标准拆分产生:

['"The', "fox's", 'foot', 'grazed', 'the', 'sleeping', 'dog,', 'waking', 'it."']

您将永远无法匹配The,fox或。dogit

有几种方法可以处理它。我正在拆分一个或多个非字母字符。lexnorm如果单词由 az 以外的字符组成,则可能需要“tweeked” :

re.split(r'[^a-zA-z]+',  '"The fox\'s foot grazed the sleeping dog, waking it."')

产量:

['', 'The', 'fox', 's', 'foot', 'grazed', 'the', 'sleeping', 'dog', 'waking', 'it', '']

一旦将行拆分为单词,就会在lexnorm字典中查找每个单词,如果找到,则在原始行中对该单词进行简单替换。最后,该行和对该行所做的任何替换都将写入一个新文件。然后,您可以删除旧文件并重命名新文件。

想想如果首先将它们转换为小写,您将如何处理匹配的单词。

更新(重大优化)

由于一个文件中很可能有很多重复的单词,一个优化是对每个唯一的单词处理一次,如果文件不是太大以至于无法读入内存,可以这样做:

import json, re

with open('lexnorm.txt') as f:
    lexnorm = json.load(f) # read back lexnorm dictionary

with open("corpus.txt", 'r', encoding='utf8') as main:
    text = main.read()
word_set = set(re.split(r'[^a-zA-z]+', text))
for word in word_set:
    if word in lexnorm:
        text = text.replace(word, lexnorm[word])
with open("corpus.txt", 'w', encoding='utf8') as main:
    main.write(text)

这里将整个文件读入text,拆分成单词,然后将单词添加到word_set保证单词唯一性的集合中。word_set然后在整个文本中查找并替换每个单词,并将整个文本重写回原始文件。


推荐阅读