簡體   English   中英

如果字符串包含列表中的后綴,如何從字符串中刪除該特定后綴?

[英]If a string contains a suffix from a list, how do I strip that specific suffix from the string?

我有一個字符串列表和一個后綴列表。 如果字符串包含后綴之一,如何從字符串中刪除該特定后綴?

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

我建議將詞干刪除分離為自己的函數,然后對整個列表使用列表理解或單獨的函數。 這是一種方法

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

您需要知道找到了哪個結尾,因此您需要一次檢查它們,而不是嘗試一次檢查它們。 找到結尾后,您可以使用切片將其切掉。

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

更好的方法是使用正則表達式:

import re
suffix = re.compile("(%s)$" % "|".join(y))

def stemming():
    for i, word in enumerate(b):
        b[i] = suffix.sub("", word)

然后,您可以使用列表推導輕松進行詞干分析:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM