【问题标题】:Normalization on a corpus using a dictionary使用字典对语料库进行规范化
【发布时间】:2020-03-25 04:49:53
【问题描述】:

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

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

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)

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

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

有人可以帮我解决这个问题吗?我会很感激的。

【问题讨论】:

  • 您的代码可能无法正常运行。首先,y == x[1] 不是分配,即使它是 y = x[1],您也不会修改 words 中的任何内容,如果是,您只会分配一个字母。您是否尝试通过在lexnorm 中查找它们并将lexnorm[y] 替换为y 来替换words 中的整个单词y

标签: python dictionary normalization corpus


【解决方案1】:

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

有几种方法可以处理它。我正在拆分一个或多个非字母字符。如果lexnorm 中的单词由 a-z 以外的字符组成,则可能需要“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 中的每个单词,并将整个文本重写回原始文件。

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2010-10-22
    • 2020-12-31
    • 2013-05-30
    • 2016-09-16
    • 2013-06-30
    相关资源
    最近更新 更多