NLTK中的Python concordance命令

2024-06-28 10:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于NLTK中Python concordance命令的问题。首先,我举了一个简单的例子:

from nltk.book import *

text1.concordance("monstrous")

效果很好。现在,我有自己的.txt文件,我想执行相同的命令。我有一个名为“textList”的列表,想找到“CNA”这个词,所以我将命令

textList.concordance('CNA') 

但是,我错了

AttributeError: 'list' object has no attribute 'concordance'. 

在这个例子中,文本1不是列表吗?我想知道这里发生了什么事。


Tags: fromimport命令txt列表例子nltk效果
2条回答

我用这个密码搞定了:

import sys
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.text import Text

def main():
    if not sys.argv[1]:
        return
    # read text
    text = open(sys.argv[1], "r").read()
    tokens = word_tokenize(text)
    textList = Text(tokens)
    textList.concordance('is')
    print(tokens)



if __name__ == '__main__':
    main()

基于this site

.concordance()是一个特殊的nltk函数。所以你不能在任何python对象上调用它(比如你的列表)。

更具体地说:.concordance()^{} class of nltk中的一个方法

基本上,如果要使用.concordance(),必须先实例化一个文本对象,然后在该对象上调用它。

Text

A Text is typically initialized from a given document or corpus. E.g.:

import nltk.corpus  
from nltk.text import Text  
moby = Text(nltk.corpus.gutenberg.words('melville-moby_dick.txt'))

.concordance()

concordance(word, width=79, lines=25)

Print a concordance for word with the specified context window. Word matching is not case-sensitive.

所以我想这样的东西会有用(没有测试)

import nltk.corpus  
from nltk.text import Text  
textList = Text(nltk.corpus.gutenberg.words('YOUR FILE NAME HERE.txt'))
textList.concordance('CNA')

相关问题 更多 >