嗨,我想我的语法就像这样的S-> NNP VBZ NNP。然而,NNP的数量巨大并且在文件中。如何将其直接加载到语法中,或者如何确保语法从语料库中提取单词而不是指定所有单词?
答案 0 :(得分:1)
假设每个POS都有自己的文本文件,其中包含每个可能包含该标记的单词,您只需要通过阅读这些行来创建字典:
lexicon = {}
with open('path/to/the/files/NNP.txt', 'r') as NNP_File:
# 'with' automatically closes the file once you're done
# now update the 'NNP' key in your lexicon with every word in the file.
# a set seems like a good idea but it depends on your purposes
lexicon['NNP'] = set(NNP_File.readlines())
此设置适用于检查某个单词是否可以是指定的词性;你还可以翻转它并将单词作为键,如果这对你正在构建的内容更好:
for word in NNP_File.readlines():
if lexicon.has_key(word):
lexicon[word].update(['NNP'])
else:
lexicon[word] = set(['NNP'])
如果文本文件的格式不同,则需要采用不同的方法。 编辑要以您提到的格式制作语法行,您可以按照上述第一种方法进行操作,例如,
with open('path/NNP.txt', 'r') as f:
NNP_terminal_rule = 'NNP -> ' + '|'.join(f)
# str.join() takes an iterable, so the file object works here.