简体   繁体   English

如何用python替换句子中的特定单词

[英]how to replace specific word in a sentence with python

I have a sentence for example "hello this is hello stackoverflow hello". 我有一个句子,例如“你好,这是你好stackoverflow你好”。 What I need to do is keep the first hello but remove other "hello"s in the sentence. 我需要做的是保持第一个问候,但删除句子中的其他“ hello”。 How would I go about doing this? 我将如何去做呢?

parts = old.split("hello")
parts[1:1] = "hello"
new = "".join(parts)

Seems like there should be a better way... 似乎应该有更好的方法...

Must be faster than Ned's one, but the price is readability: 必须比内德的快,但价格是可读性:

>>> idx = s.find('hello') + len('hello')
>>> s[:idx] + s[idx:].replace('hello', '')
'hello this is  stackoverflow '
>>> s = 'hello this is hello stackoverflow hello'
>>> head, sep, tail = s.partition('hello')
>>> head + sep + tail.replace('hello', '')
'hello this is  stackoverflow '

Very bad way: 很糟糕的方法:

s = "hello this is hello stackoverflow hello"
s = s.replace("hello", "world").replace("world", "hello", 1)

It will replace all the hello by world , then replace only the first world by hello 它将用world替换所有的hello ,然后用hello只替换第一个world

s = "hello this is hello stackoverflow hello"
t = "hello"

i = s.index(t) + len(t) + 1
s = s[:i] + s[i:].replace(t, "")

print s # hello this is  stackoverflow 

Firstly, everyone will see this as a matching pattern conundrum, so the question is why does hello repeat? 首先,每个人都将其视为匹配模式难题,所以问题是为什么hello重复?

If the first hello is assumed then a simple filtering of the string can fix the problem 如果假设第一次hello ,那么简单的字符串过滤就可以解决问题

s = 'hello this is hello stackoverflow hello'
l = s.split(' ')
"hello %s" % " ".join(filter (lambda a: a != 'hello', l))
'hello this is stackoverflow'

Or: 要么:

import re
s = 'hello this is hello stackoverflow hello'
re.sub('\shello\s?', ' ', s).strip()
'hello this is stackoverflow'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用python替换方法的情况下替换句子中的单词 - How to replace a word in a sentence without using the python replace method 如何在python中替换特定单词下的值? - how to replace a value under specific word in python? 在 python 中创建一个包含特定单词的有意义的句子 - Create a meaningful sentence containing specific word in python 在 Python 中查找具有给定单词的特定句子 - Find a specific sentence with a given word in Python 用python中的不同名称替换句子中的特定单词 - Replace specific words in sentence by different names in python 如何在python中的特定单词后面替换下一个单词 - How to replace next word after a specific word in python 如何从“关键字” python开始替换特定行中的特定单词 - How to replace a specific word in specific line starting with a “keyword” python 如何使用python正则表达式查找和替换句子中第n次出现的单词? - How to find and replace nth occurrence of word in a sentence using python regular expression? python-查找和替换句子中给定单词的最有效代码? - python - most efficient code to search for, and replace, given word in a sentence? 在另一个列表的句子中查找列表中的单词,并在Python 2.7中将其替换 - Find a word of a list in a sentence of another list and replace it in Python 2.7
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM