gpt4 book ai didi

python - 在 Python 中删除停用词

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:40 24 4
gpt4 key购买 nike

我正在尝试使用 .join 函数从用户输入的字符串中删除停用词。它看起来像这样:

while True:
line = raw_input()
if line.strip() == stopword:
break
remove_stopwords = ''.join(word for word in line.split() if word not in stop_words)

我在顶部的列表中定义了 stop_words。问题是,当我输入要从中删除的停用词的字符串时,它只会删除第一个词并保留其余词。任何帮助都会很棒。我是新手,所以这可能有些愚蠢。

最佳答案

这是一个使用 filter 的单衬垫功能:

" ".join(filter(lambda word: word not in stop_words, line.split()))

此外,请考虑将停用词存储在集合 而不是列表 中。搜索操作 (in) 的平均算法复杂度对于 set 是常量,对于 list 是线性的。

编辑:您的程序似乎按预期工作,并为 join 字符串添加了额外的空间。这是有道理的,因为 (x for x in y if f(x)) 大致等同于 filter:

  stop_words = set(["hi", "bye"])
stopword = "DONE"
while True:
line = raw_input()
if line.strip() == stopword:
break
print(" ".join(word for word in line.split() if word not in stop_words))

输入:

hello hi my name is bye justin

输出:

hello my name is justin

你的错误一定在你程序的其他地方。你还在做什么?

关于python - 在 Python 中删除停用词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20315362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com