-1

With reference to both of these links:

I am trying to use this method to be able to replace from a user inputted string using a dictionary created from a CSV but with case insensitivity.

The solution in question is as follows:

string=input("Please enter your string")
pattern = re.compile(r'(?<!\w)(' + '|'.join(re.escape(key) for key in sorted(dict.keys(),key=len, reverse=True)) + r')(?!\w)')
result = pattern.sub(lambda x: dict[x.group()], string)
print(result)

now I've tried using the RE.IGNORECASE method on the end of my compile, as well as using the "Case Insensitive Dictionary Method" to change my initial dictionary but no matter each method I try I keep getting the same error whenever the input isn't an exact match for the keywords "Key Error 'keyword' doesn't match".

1
  • Please post the whole reproducible example. Commented Mar 7, 2019 at 20:38

1 Answer 1

0

Supposing your dictionary keys only have lower case words or only uppercase words, you could do something like this:

import re
dict = {'KEYWORD': "replacement_keyword", 'EXAMPLE': 'b', 'EXAMPLE2: 2': 'c'}
string=input("Please enter your string")
pattern = re.compile(r'(?<!\w)(' + '|'.join(re.escape(key) for key in sorted(dict.keys(), key=len, reverse=True)) + r')(?!\w)', re.IGNORECASE)
result = pattern.sub(lambda x: dict[str.upper(x.group())], string)
print(result)

By using str.upper or str.lower in case your keys are lower cases, you match your keys.

The Output yields:

Please enter your string: Keyword KEYWORD keyWord
replacement_keyword replacement_keyword replacement_keyword

I hope this solves, what you want to achieve, otherwise please provide more context.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.