简体   繁体   中英

Remove single word after keyword

Python Script to remove names after 'Dear' keyword I have a string of case comments and I am trying to remove people's name after the word 'Dear'. For example, my string might be 'Dear Jane, I am having an issue with one of the products.' and I want my script to find 'Dear' and then remove the following word 'Jane'. My script identifies 'Dear', but deletes everything after not just the name:

text = 'Dear Jane, I am having an issue with one of the products.'

text = ''.join(text.partition('Dear')[:2])

print(text)

If you want to leave Dear , but remove the name, you can use a regular expression and re.sub here:

>>> import re
>>> re.sub(r'(Dear)\s\w+', r'\1', text)
'Dear, I am having an issue with one of the products.'

If you want to remove Dear too, you can change your regular expression:

>>> re.sub(r'Dear\s\w+[^\w]+', '', text)
'I am having an issue with one of the products.'

For any advanced text processing use re builtin module:

import re
text = 'Dear Jane, I am having an issue with one of the products.'

print(re.sub('^Dear\s(.*?),', 'Dear,', text))

Output:

Dear, I am having an issue with one of the products.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM