如何解决nltk 在生成三元组时不插入句尾符号 试试以下方法:
我正在使用 Kneser-Ney 平滑从霍比特人生成文本。我的模型正在生成句子,但我相信还有改进的空间。
目前,我不使用符号来标记句子的开头和结尾。 当我尝试使用下面的代码插入它们时,我只能看到句子符号的第一个开头存在,但不知何故,对于其余的句子,没有插入符号。几乎就好像它根本没有检测到句子的结尾。
我尝试不将文本转换为小写,但没有任何改变。
你能告诉我如何插入句尾符号吗?
with open ("hobbit.txt") as f:
hobbit_text = f.read()
hobbit_text = word_tokenize(hobbit_text.lower())
stop_words = stopwords.words('english')
personal_names = ['legolas','gimli','boromir','frodo','thorin','thror','gandalf','smeagol','gollum','balin','elrond','aragorn','bilbo','sauron']
signs = ['”','“','!','?','’','`',"'",'``',',";","(",")"]
use_stop_words = True
use_punctuation = False
# get rid of stop words,punctuation (if necessary)
if not use_stop_words:
hobbit_text = [x for x in hobbit_text if x not in stop_words]
if not use_punctuation:
hobbit_text = [x for x in hobbit_text if x not in signs]
vocab = set(hobbit_text)
counter = 0
hobbit_trigram = ngrams(hobbit_text,3,pad_left=True,pad_right=True,left_pad_symbol='BOS',right_pad_symbol='EOS')
for a in hobbit_trigram:
print(a)
counter += 1
if counter == 100:
break
第一句话的输出如下所示。我期待在“金”这个词之后的句尾符号。
('BOS','BOS','the')
('BOS','the','霍比特人')
('the','hobbit','or')
('霍比特人','或','那里')
('or','there','and')
('那里','和','后面')
('and','back','again')
('返回','再次','j.r.r')
('再次','j.r.r','.')
('j.r.r','.','托尔金')
('.','托尔金','the')
('托尔金','is')
('霍比特人','是','a')
('是','a','故事')
('a','故事','of')
('故事','of','high')
('of','high','冒险')
('high','adventure','承担')
('冒险','承担','by')
('承担','by','a')
('by','公司')
('a','company','of')
('company','dwarves')
('of','dwarves','in')
('矮人','in','搜索')
('in','search','of')
('搜索','守龙')
('of','守龙','黄金')
('守龙','黄金','.')
('金','a')
解决方法
试试以下方法:
from functools import partial
from nltk import ngrams
padded_ngrams = partial(ngrams,pad_left=True,pad_right=True,left_pad_symbol='BOS',right_pad_symbol='EOS')
padded_hobbit_text = list(padded_ngrams(hobbit_text,3))
# now print your value to see if it's what you want
print(padded_hobbit_text)
# with an input of "TEXT",it gave me the following output
'''
[('BOS','BOS','T'),('BOS','T','E'),('T','E','X'),('E','X',('X','EOS'),'EOS','EOS')]
'''
我试过这样做,它给了我方便的格式,就像你在问题中提出的那样。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。