我有一个字符串和一个短语数组。
input_string = 'alice is a character from a fairy tale that lived in a wonder land. A character about whome no one knows much about'
phrases_to_remove = ['wonderland', 'character', 'no one']
现在我想做的是,从input_string
中删除数组phrases_to_remove
中单词的最后一次出现。
output_string = 'alice is a character from a fairy tale that lived in a. A about whome knows much about'
我已经写了一个函数,它接受一个输入字符串以及要替换的
数组
或仅仅是一个字符串
。我使用了 rsplit()
方法来进行短语替换。def remove_words_from_end(actual_string: str, to_replace, occurrence: int):
if isinstance(to_replace, list):
output_string = actual_string
for string in to_replace:
output_string = ' '.join(output_string.rsplit(string, maxsplit=occurrence))
return output_string.strip()
elif isinstance(to_replace, str):
return ' '.join(actual_string.rsplit(to_replace, maxsplit=occurrence)).strip()
else:
raise TypeError('the value "to_replace" must be a string or a list of strings')
代码的问题在于,我无法删除具有空格不匹配的单词。例如wonder land
和wonderland
。
有没有一种方法可以在不牺牲太多性能的情况下解决这个问题?
wonderland
时同时将wonder land
删除,那么当被要求删除nowhere
时,你是否也希望将now here
删除?如何区分“空格不匹配”和合法的空格? - John Colemanre.sub(phrases_to_remove[0], '' , input_string)
。 - jackotonyere
如何处理空格
? - iam.Carrot