-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".

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Starcross
  • 3
  • 2

1 Answers1

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.

David
  • 2,926
  • 1
  • 27
  • 61