在 NLTK 文本中找到一个句子? ```.find``` 和 ```.index``` 不起作用

问题描述 投票:0回答:0

我在文本上运行 nltk concordance 命令,我得到了一些例句。如何找到返回句子在文本中的位置?

.find
.index
不适用于 nltk 使用的文本实体。

我使用的代码如下。这是 nltk 书中的一个简单示例。我得到一条线。

and Pesant slaue am I ? Is it not monstrous that this Player heere , But in a

当我尝试时,

found_text = hamlet_text.find("Is it not monstrous that this Player heere")

它给了我这个错误

AttributeError: 'Text' object has no attribute 'find'

当我尝试时,

found_text = hamlet_text.index("Is it not monstrous that this Player heere")

它给了我这个错误,因为这个句子不是列表中的一个项目。

ValueError: 'Is it not monstrous that this Player heere' is not in list

那么如何在 nltk 文本实体中找到该句子开始的文本位置?我应该使用什么命令来复制

.find
.index
的功能?

谢谢。

#import the Natural Language Tool Kit
import nltk 

nltk.download('punkt') 
from nltk.tokenize import sent_tokenize, word_tokenize

from nltk.text import Text

hamlet = open('shakespeare-hamlet.txt', 'r') 

hamlet_read = hamlet.read() 
print(hamlet_read[1:200]) 

hamlet_text = nltk.Text(nltk.word_tokenize(hamlet_read))
#print the first 200 characters so we can see what we have.  
print(hamlet_text[1:200]) 

hamlet_text.concordance("monstrous")```
python nltk
© www.soinside.com 2019 - 2024. All rights reserved.