Python NLTK防止停止字删除删除每个字

2024-05-15 13:54:05 发布

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

我用的是很短的字串,其中有几个是愚蠢的。假设,我可以有一个字符串“youana”,如果我去掉非索引字,这个字符串将是空白的。因为我是在循环中分类的,所以如果它是一个空字符串,它就会停止并返回一个错误。我创建了以下代码来修复此问题:

def title_features(words):
filter_words = [word for word in words.split() if word not in stopwords.words('english')]
features={}
if len(filter_words) >= 1:
    features['First word'] = ''.join(filter_words[0])
else:
    features['First word'] = ''.join(words.split()[0])
return features

这确保了我不会出错,但我想知道是否有更有效的方法来做到这一点。或者是一种方法,它不会去掉所有的单词,如果它们都是停止语的话。在


Tags: 方法字符串inif分类filter空白word
2条回答

最简单的解决方案是检查筛选结果,必要时恢复完整的单词列表。然后剩下的代码就可以使用一个变量而不需要检查。在

def title_features(words):
    filter_words = [word for word in words.split() if word not in stopwords.words('english')]
    if not filter_words:       # Use full list if necessary
        filter_words = words

    features={}
    features['First word'] = filter_words[0]
    features[...] = ...

    return features

您可以重写为:

def title_features(words):
    filtered = [word for word in words.split() if word not in stopwords.words('english')]
    return {'First word': (filtered or words.split(None, 1) or [''])[0]}

如果它不是空的(例如-有一个或一个以上的长度),或者如果它是空的,则需要filtered,然后继续拆分原始的,如果是空的,则默认为一个带有空字符串的单元素列表。然后使用[0]中的任何一个来获取第一个元素(第一个非停止单词、字符串的第一个单词或一个空字符串)。在

相关问题 更多 >