替换所有出现的特定单词 [英] Replace all the occurrences of specific words

查看:53
本文介绍了替换所有出现的特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下句子:

bean 喜欢卖他的豆子

我想用其他词替换所有出现的特定词.例如,beanrobertbeanscars.

我不能只使用str.replace,因为在这种情况下,它会将beans 更改为roberts.

<预><代码>>>>"bean 喜欢卖他的豆子".replace("bean","robert")'罗伯特喜欢卖他的罗伯茨'

我只需要更改整个单词,而不是该单词在另一个单词中的出现次数.我认为我可以通过使用正则表达式来实现这一点,但不知道该怎么做.

解决方案

如果你使用正则表达式,你可以用 \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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆