Methods.endswith/.removesuffix)不删除后缀



我正在尝试删除后缀,但由于某种原因,它不起作用。代码为:

# Stemming
suffix_list = ['-ed', '-ing', '-s']
for word in range(len(output)):  # loop
# range returns the sequence, len checks the lenght
for suffix in range(len(suffix_list)):
# .endswith checks x in both
if output[word].endswith(suffix_list[suffix]):
# .removesuffix removes from output if in suffix_list
print(output[word].removesuffix(suffix_list[suffix]))
return output
print(textPreprocessing("I'm gathering herbs."))
print(textPreprocessing("When life gives you lemons, make lemonade"))

结果是:

gather
herb
['im', 'gathering', 'herbs']
give
lemon
['life', 'gives', 'you', 'lemons', 'make', 'lemonade']

应该在哪里:

['im', 'gather', 'herbs']
['life', 'give', 'you', 'lemon', 'make', 'lemonade']

有什么帮助吗?我觉得我错过了一些显而易见的东西。。。

output[word] = output[word].removesuffix(suffix_list[suffix])

这将起作用:-

str_sample = "When life gives you lemons make lemonade"
suffixes, words = ["s"], str_sample.split()
for i in range(len(suffixes)):
for j in range(len(words)):
if words[j].endswith(suffixes[i]):
words[j] = words[j].replace(f"{suffixes[i]}", "")
print(words)

它可以压缩为列表理解为:-

str_sample = "When life gives you lemons make lemonade"
suffixes, words = ["s"], str_sample.split()
res = [words[j].replace(f"{suffixes[i]}", "") if words[j].endswith(suffixes[i]) else words[j] for j in range(len(words)) for i in range(len(suffixes))]
print(words)

最新更新