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')]
'''

我试过这样做,它给了我方便的格式,就像你在问题中提出的那样。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...