如果一个字符串包含列表中的后缀,我如何从该字符串中去掉该后缀?

2024-10-16 22:32:42 发布

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

我有一个字符串列表和一个后缀列表。如果一个字符串包含其中一个后缀,我如何从该字符串中去掉该后缀?在

b = ["food", "stuffing", "hobbitses"]
y = ["ing", "es", "s", "ly"]


def stemming():
    for i in range(len(b)):
        if b[i].endswith(tuple(y)):
            b[i] = b[i] - #???
print b

Tags: 字符串in列表forlenesfooddef
3条回答

你需要知道找到了哪个结尾,所以你需要一次检查一个,而不是一次检查所有的结尾。一旦你找到了一个结尾,你可以用切片把它切掉。在

def stemming():
    for i, word in enumerate(b):
        for suffix in y:
            if word.endswith(suffix):
                b[i] = word[:-len(suffix)]
                break

更好的方法是使用正则表达式:

^{pr2}$

然后,您可以使用列表理解轻松地进行词干分析:

b = [suffix.sub("", w) for w in b]

我建议将词干删除分离成它自己的函数,然后对整个列表使用列表理解或单独的函数。这里有一种方法

def remove_stems(word, stems):
    for stem in stems:
        if word.endswith(stem):
            return word[:-len(stem)]
        else: 
            return word

b_without_stems = [remove_stem(word, stems) for word in b]

假设你想去掉找到的第一个后缀,这个就可以了

def stemming(strings, endings):
    for i, string in enumerate(strings):
        for ending in endings:
            if string.endswith(ending):
                strings[i] = string[:-len(ending)]
                continue

相关问题 更多 >