我在使用nltk消除和标记.text文件时遇到困难。我不断收到以下错误消息:AttributeError:“列表”对象没有属性“较低”。尽管这是我第一次做这样的事情,但我只是无法弄清楚自己在做什么错。以下是我的代码行。如果有任何建议,我将不胜感激,谢谢
Import nltk
from nltk.corpus import stopwords
s = open("C:\zircon\sinbo1.txt").read()
tokens = nltk.word_tokenize(s)
def cleanupDoc(s):
stopset = set(stopwords.words('english'))
tokens = nltk.word_tokenize(s)
cleanup = [token.lower()for token in tokens.lower() not in stopset and len(token)>2]
return cleanup
cleanupDoc(s)
您可以使用NLTK的stopwords
列表,请参阅How to remove stop words using nltk or python。
而且很可能您还希望删除标点符号,可以使用string.punctuation
,请参见http://docs.python.org/2/library/string.html:
>>> from nltk import word_tokenize
>>> from nltk.corpus import stopwords
>>> import string
>>> sent = "this is a foo bar, bar black sheep."
>>> stop = stopwords.words('english') + list(string.punctuation)
>>> [i for i in word_tokenize(sent.lower()) if i not in stop]
['foo', 'bar', 'bar', 'black', 'sheep']
import nltk
from nltk.corpus import stopwords
def cleanupDoc(s):
stopset = set(stopwords.words('english'))
tokens = nltk.word_tokenize(s)
cleanup = " ".join(filter(lambda word: word not in stopset, s.split()))
return cleanup
s = "I am going to disco and bar tonight"
tokens = nltk.word_tokenize(s)
x = cleanupDoc(s)
print x
此代码可以帮助解决上述问题。
根据错误消息,您似乎正在尝试将列表而不是字符串转换为小写。您的tokens = nltk.word_tokenize(s)
可能未返回您期望的值(这似乎是一个字符串)。
知道您的sinbo.txt
文件采用什么格式会很有帮助。
一些语法问题:
导入应为小写:import nltk
行s = open("C:\zircon\sinbo1.txt").read()
正在读取整个文件,而不是一次读取一行。这可能是有问题的,因为word_tokenize有效on a single sentence,而不是任何令牌序列。当前行假定您的sinbo.txt
文件包含一个句子。如果不是,您可能想要(a)在文件上使用for循环,而不是使用read(),或(b)在整堆由标点符号分隔的句子上使用punct_tokenizer。
cleanupDoc
函数的第一行未正确缩进。您的函数应该看起来像这样(即使其中的函数发生了变化)。
import nltk
from nltk.corpus import stopwords
def cleanupDoc(s):
stopset = set(stopwords.words('english'))
tokens = nltk.word_tokenize(s)
cleanup = [token.lower() for token in tokens if token.lower() not in stopset and len(token)>2]
return cleanup
在您的特定情况下,错误是cleanup = [token.lower()for token in tokens.lower() not in stopset and len(token)>2]
令牌是一个列表,因此您不能在列表上执行tokens.lower()操作。因此,编写上述代码的另一种方式是,
cleanup = [token.lower()for token in tokens if token.lower() not in stopset and len(token)>2]
我希望这会有所帮助。