python - 将条件变量与 nltk 的索引模块一起使用

标签 python conditional-statements nltk

我刚刚开始使用 nltk,但在让索引模块处理条件变量时遇到问题。我想返回拉丁文本中任何给定单词的索引,但由于该语言是变形的,我希望能够指定词干,识别语料库中包含该词干的任何单词,并返回该词的索引。我使用的代码是:

book1 = open('Book1.txt', 'rU').read()
token1 = nltk.word_tokenize(book1)
text1 = nltk.Text(token1)

word = raw_input("What stem do you want to search?\n > ")

text1.concordance([w for w in text1 if w.startswith(word)])

返回错误:

    Traceback (most recent call last):
  File "C:\Users\admin\Desktop\start_nltk_horace.py", line 68, in <module>
    concordance()
  File "C:\Users\admin\Desktop\start_nltk_horace.py", line 49, in concordance
    text1.concordance([w for w in text1 if w.startswith(word)])
  File "C:\Python27\lib\site-packages\nltk\text.py", line 314, in concordance
    self._concordance_index.print_concordance(word, width, lines)
  File "C:\Python27\lib\site-packages\nltk\text.py", line 177, in print_concordance
    offsets = self.offsets(word)
  File "C:\Python27\lib\site-packages\nltk\text.py", line 156, in offsets
    word = self._key(word)
  File "C:\Python27\lib\site-packages\nltk\text.py", line 312, in <lambda>
    key=lambda s:s.lower())
AttributeError: 'list' object has no attribute 'lower'

只需指定 text1.concordance(word) 返回我正在寻找的内容,没有任何问题(假设我输入完全拒绝的单词),但我必须重复该功能六次左右需要花费很多时间才能获得一个单词的所有不同词形变化的索引。

最佳答案

我认为问题在于您试图向 NLTK 的 concordance() 函数提供单词列表,而它只接受字符串。请尝试以下操作:

my_concordances = []
my_inputs = [elem for elem in text1 if elem.startswith(word)]
for input in my_inputs:
    my_concordances.append(text1.concordance(input))

然后,my_concordances 应该以一个列表的形式结束,其中每个条目都是以原始输入字符串开头的不同单词的索引。您还可以考虑根据 concordance() 函数返回的特定数据类型为 my_concordances 预分配空间,因为您只需检查 的长度>我的输入。如果出现问题,这可能会提高速度。

请注意this question您可能也会感兴趣。它更详细地介绍了 concordance()

关于python - 将条件变量与 nltk 的索引模块一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777871/

相关文章:

python - 如何使用 scikit-learn 加载文件并处理 .txt 文件?

python - 如何使用 Selenium 向 ChromeDriver 提交 HTTP 身份验证(Flask BASIC Auth)

python - Python 中的代码块

python - django查询用于对作为外键出现的字段上的数据进行排序

c - 重复输入直到回答正确

将所有结构项与特定规则进行比较

c++ - 游戏连续输入检查

machine-learning - 用于文本分类的 nltk naivebayes 分类器

python - Python 函数中的最大参数数是多少?

python - 如何使用 Python 在 Wordnet 中查找相关性