替换所有出现的特定单词 [英] Replace all the occurrences of specific words
问题描述
假设我有以下句子:
bean 喜欢卖他的豆子
我想用其他词替换所有出现的特定词.例如,bean
到 robert
和 beans
到 cars
.
我不能只使用str.replace
,因为在这种情况下,它会将beans
更改为roberts
.
我只需要更改整个单词,而不是该单词在另一个单词中的出现次数.我认为我可以通过使用正则表达式来实现这一点,但不知道该怎么做.
如果你使用正则表达式,你可以用 \b
指定单词边界:
导入重新句子 = '豆子喜欢卖他的豆子'句子 = re.sub(r'\bbean\b', 'robert', 句子)#'罗伯特喜欢卖他的豆子'
此处 'beans' 未更改(更改为 'roberts'),因为末尾的 's' 不是单词之间的边界:\b
匹配空字符串,但 仅 在单词的开头或结尾.
完整性的第二个替换:
sentence = re.sub(r'\bbeans\b', 'cars', sentence)#罗伯特喜欢卖他的车"
Suppose that I have the following sentence:
bean likes to sell his beans
and I want to replace all occurrences of specific words with other words. For example, bean
to robert
and beans
to cars
.
I can't just use str.replace
because in this case it'll change the beans
to roberts
.
>>> "bean likes to sell his beans".replace("bean","robert")
'robert likes to sell his roberts'
I need to change the whole words only, not the occurrences of the word in the other word. I think that I can achieve this by using regular expressions but don't know how to do it right.
If you use regex, you can specify word boundaries with \b
:
import re
sentence = 'bean likes to sell his beans'
sentence = re.sub(r'\bbean\b', 'robert', sentence)
# 'robert likes to sell his beans'
Here 'beans' is not changed (to 'roberts') because the 's' on the end is not a boundary between words: \b
matches the empty string, but only at the beginning or end of a word.
The second replacement for completeness:
sentence = re.sub(r'\bbeans\b', 'cars', sentence)
# 'robert likes to sell his cars'
这篇关于替换所有出现的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!