在Python中通过列表过滤文本

2024-10-01 05:02:58 发布

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

我有一个stopword列表(德语),我想用它从输入文本中过滤出相同的单词,如下所示:

stopwortlist = ['ab', 'aber','abgesehen', 'alle', 'allein', 'aller', 'alles']
text = input('please put in a Text')
#i have found a way of controlling them online, but it doesnt quite work,
#cause it gives out a list, and all i want is a text (where the words from 
#the list are filtered out

def filterStopwords (eingabeText, stopwords):

    out = [word for word in eingabeText if word not in stopwords]
    return out;

如何修改函数以获得结果? 事先非常感谢


Tags: thetextin文本列表abitout
2条回答

下面是一个使用filter和join方法的一个单行程序。在

stopwortlist = ['ab', 'aber','abgesehen', 'alle', 'allein', 'aller', 'alles']
text = 'There are ab aber multiple allein abgesehen words in alles this ab list'

print " ".join(filter(lambda x: x not in stopwortlist, text.split()))

#Output
There are multiple words in this list

这基本上使用lambda函数来检查单词是否在stopwortlist中,然后将其从字符串中筛选出来。在

将输入的文本拆分为单词(否则将迭代字符),过滤停止单词,然后重新加入结果列表。在

stopwortlist = ['ab', 'aber','abgesehen', 'alle', 'allein', 'aller', 'alles']
text = 'Some text ab aber with stopwords allein in'

def filterStopwords(eingabeText, stopwords):
    out = [word for word in eingabeText.split() if word not in stopwords]
    return ' '.join(out)

filterStopwords(text, stopwortlist) # => 'Some text with stopwords in'

相关问题 更多 >