I want to replace the sentences with different name and I do not know why it is does works
text="hi, my name is angle enrico, how is everything going?"
s = text.replace(r'hi, my name is\s+','')
print(s)
I want to have an output 'how is everything going?',but I am getting'hi, my name is angle enrico, how is everything going?' Anyone know how to solve it?
It looks like you are trying to use regex syntax in a non-regex context. What your code is currently doing is searching for the literal string hi, my name is\\s+
, which clearly does not exist in your input string.
What you need to do is write a regex that will capture the beginning of the string, and then pass that into the text.replace
.
Try using:
s = text.replace('hi, my name is','')
print(' '.join(s.split()[2:]))
Or:
print(text.split(', ')[2])
Both reproduce:
how is everything going?
>>> text="hi, my name is angle enrico, how is everything going?"
>>> pre = text[text.index("hi, my name is ")+len("hi, my name is "):]
>>> pre
'angle enrico, how is everything going?'
>>> suf = pre[pre.index(", ")+len(", "):]
>>> suf
'how is everything going?'
You need to use a regex and the re module.
You want to replace the part of the string starting with 'Hi, my name is', followed by anything ( .*
), then a comma and at least one space ( ,\\s+
).
If the end of the sentence can contain commas as well, you need to take the smallest possible 'anything', so you have to do it in a non-greedy way ( .*?
).
So, you could do:
import re
text="hi, my name is angle enrico, how is everything going?"
s = re.sub(r'hi, my name is .*?,\s+', '', text)
print(s)
#how is everything going?
It also works with a second comma further in the sentence:
text="hi, my name is fred, I'm fine, thanks!"
s = re.sub(r'hi, my name is .*?,\s+', '', text)
print(s)
#I'm fine, thanks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.