I want to extract tags - "Satisfied" or "Not Satisfied" from a string in python…
- User
I want to extract tags - "Satisfied" or "Not Satisfied" from a string in python irrepective of tags
- Assistant
To extract tags like "Satisfied" or "Not Satisfied" from a string in Python, regardless of where these tags are situated within the string or how they are capitalized, you can use regular expressions. Python's
remodule is perfect for this kind of pattern matching and extraction.Below is an example function that searches for both "Satisfied" and "Not Satisfied" in the input text. It assumes that the tags can appear in any case (e.g., lower, upper, title).
import re def extract_satisfaction_tags(text): # This regular expression looks for 'satisfied' or 'not satisfied' in a case-insensitive manner pattern = re.compile(r'\b(not\s)?satisfied\b', re.IGNORECASE) matches = pattern.findall(text) # Each match is a tuple because of the capturing group, transform it into a more readable form tags = [' '.join(match).strip() for match in matches] # Print or return the tags based on your preference return tags # Example usage text = "I am completely not satisfied with the service. However, later I felt somewhat satisfied." tags_found = extract_satisfaction_tags(text) print(tags_found)