使用字典对语料库进行规范化



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

我采取了这里讨论的一种方法。代码如下:

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)

上面的代码运行得很好,但我遇到了一个问题,因为字典里有成千上万的单词对。可以通过文本文件表示字典吗?

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

有人能帮我吗?我会很感激的。

将字典输出为文本文件的一种方法是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."']

您永远无法匹配Thefoxdogit

有几种方法可以处理它。我正在拆分一个或多个非alpha字符。如果lexnorm中的单词由a-z:以外的字符组成,则可能需要"粗花呢">

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中的每个单词并将其替换为整个文本,然后将整个文本重写回原始文件。

最新更新