Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
nltk python的这段代码有什么问题_Python_Nltk - Fatal编程技术网

nltk python的这段代码有什么问题

nltk python的这段代码有什么问题,python,nltk,Python,Nltk,我不明白为什么这段代码不能返回一个列表,它只返回一个标记/单词,执行后您的return语句处于循环中,这意味着只要单词中的标记与匹配,函数就会立即返回。要纠正这个问题,只需将返回移出循环,如下所示:(为了简单起见,我删除了打开文件的部分。这只是一个测试。您必须让您的方法读取该文件) 结果是 import nltk def ethos(): raw = 'i love well made products' tokens = nltk.word_tokenize(raw)

我不明白为什么这段代码不能返回一个列表,它只返回一个标记/单词,执行后您的
return
语句处于循环中,这意味着只要单词中的
标记与
匹配,函数就会立即返回。要纠正这个问题,只需将
返回
移出循环,如下所示:(为了简单起见,我删除了打开文件的部分。这只是一个测试。您必须让您的方法读取该文件)

结果是

import nltk

def ethos():
    raw = 'i love well made products'
    tokens = nltk.word_tokenize(raw)
    words_to_match = ['love' , 'good' , 'excellent' , 'perfect' , 'brilliant' , 'easy' , 'well' , 'made' , 'impressive' , 'great']
    matching_tokens = []
    for tokens in tokens:
        if tokens in words_to_match:
            matching_tokens.append(tokens)
    return matching_tokens

print ethos()

它似乎起作用了

我尝试了这个,但结果是一样的/并且知道
标记
在循环之前有什么值会很有帮助。我将一个文本文件转换为标记,然后希望所有标记都与匹配标记列表匹配。我知道程序应该做什么。如果你能给出具体的例子,说明出了什么问题,那会很有帮助。只是一个样本,你期望的,你实际得到的,我得到了这个['well'],我想要一个像['good','love','Applied',…]这样的列表。。。糟糕的标题,更糟糕的问题。
import nltk

def ethos():
    raw = 'i love well made products'
    tokens = nltk.word_tokenize(raw)
    words_to_match = ['love' , 'good' , 'excellent' , 'perfect' , 'brilliant' , 'easy' , 'well' , 'made' , 'impressive' , 'great']
    matching_tokens = []
    for tokens in tokens:
        if tokens in words_to_match:
            matching_tokens.append(tokens)
    return matching_tokens

print ethos()
['love', 'well', 'made']