python - 从自定义转储创建供 Webnet 使用的信息内容语料库

标签 python nltk wordnet corpus pos-tagger

我正在使用 Brown 语料库 ic-brown.dat 使用 wordnet nltk 库计算单词的信息内容。但结果并不好看。我想知道如何构建自己的custome.dat(信息内容文件)。

custom_ic = wordnet_ic.ic('custom.dat')

最佳答案

(...)/nltk_data/corpora/wordnet_ic/中,您会发现IC-compute.sh,其中包含对一些Perl脚本的调用以生成IC来自给定语料库的 dat 文件。我发现这些指令很棘手,而且我没有所需的 Perl 脚本,所以我决定通过分析 dat 文件结构和 wordnet.ic() 函数来创建一个 python 脚本。

您可以通过对语料库阅读器对象调用 wordnet.ic() 函数来计算您自己的 IC 计数。事实上,您只需要一个带有 word() 函数的对象,该函数返回语料库中的所有单词。有关更多详细信息,请检查文件 ..../nltk/corpus/reader/wordnet.py 中的 ic 函数(第 1729 至 1789 行)。

例如,对于 BNC 语料库 (2007) 的 XML 版本:

reader_bnc = nltk.corpus.reader.BNCCorpusReader(root='../Corpus/2554/2554/download/Texts/', fileids=r'[A-K]/\w*/\w*\.xml')
bnc_ic = wn.ic(reader_bnc, False, 0.0)

为了生成 .dat 文件,我创建了以下函数:

def is_root(synset_x):
    if synset_x.root_hypernyms()[0] == synset_x:
        return True
    return False

def generate_ic_file(IC, output_filename):
    """Dump in output_filename the IC counts.
    The expected format of IC is a dict 
    {'v':defaultdict, 'n':defaultdict, 'a':defaultdict, 'r':defaultdict}"""
    with codecs.open(output_filename, 'w', encoding='utf-8') as fid:
        # Hash code of WordNet 3.0
        fid.write("wnver::eOS9lXC6GvMWznF1wkZofDdtbBU"+"\n")

        # We only stored nouns and verbs because those are the only POS tags
        # supported by wordnet.ic() function
        for tag_type in ['v', 'n']:#IC:
            for key, value in IC[tag_type].items():
                if key != 0:
                    synset_x = wn.of2ss(of="{:08d}".format(key)+tag_type)
                    if is_root(synset_x):
                        fid.write(str(key)+tag_type+" "+str(value)+" ROOT\n")
                    else:
                        fid.write(str(key)+tag_type+" "+str(value)+"\n")
    print("Done")

generate_ic_file(bnc_ic, "../custom.dat")

然后,只需调用该函数即可:

custom_ic = wordnet_ic.ic('../custom.dat')

所需的导入是:

import nltk
from nltk.corpus import wordnet as wn
from nltk.corpus import wordnet_ic
import codecs

关于python - 从自定义转储创建供 Webnet 使用的信息内容语料库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436663/

相关文章:

python - 从 NLTK 语料库中检索句子字符串

python-3.x - Spacy相似警告: "Evaluating Doc.similarity based on empty vectors."

python - 在 setup.py 脚本中安装 nltk 数据依赖

python - 如何将 Altair 图表设置为特定增量?

python - 如何创建一个具有特定 len 的 python 数组,每个元素都初始化为 0

python - MinMaxScaler 如何工作 - 按行缩放还是针对整个数据集缩放?

python - `type` 和 `tuple` 的子类

python - NLTK - 缺少停用词 - 英语

python - 计算标记化词中的词频 - 使用 else if 逻辑

python - 如何使用nltk找出英语中是否存在单词