I'm trying to check if my dict keys can be found in a string. The thing is that my code doesn't match the entire string as such but goes through each character.
I tried like so:
val_dict= {'1/2 pint': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text:
print(x, val_dict.get(x))
But I'm getting
1/2 pint half
1 one
Instead of only 'half'. How to solve it? '/' is not an escape character as far as I know.
Edit: Given the solutions provided in other topics, I tried regular expressions:
for x in val_dict:
if re.search(rf"\b{x}\b", text, re.IGNORECASE):
print(x + " match")
>>> 1/2 pint match
>>> 1 match
which is ok, because of \\b
but:
for x in val_dict:
if re.search(rf"^{x}$", text, re.IGNORECASE):
print(x + " match")
Should match exact occurrence, but gives no result. Why?
Please note that my dict keys may contain spaces, so splitting the text by spaces won't work.
This is the fix:
val_dict= {'1/2': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text.split(' '):
print(x, val_dict.get(x))
Output
1/2 half
You can try using Regular Expressions
import re
val_dict= {r'1/2': 'half', r'1[!/]': 'one', '5': 'five'}
# ^"1/2"^ ^ 1 with NO SLASH
text = 'I need 1/2 pint of beer'
for x in val_dict:
if re.match(x, text):
print(x, val_dict.get(x))
Expected output:
1/2 half
You can tailor RegEx to much better fit your needs!
I'm trying to check if my dict keys can be found in a string. The thing is that my code doesn't match the entire string as such but goes through each character.
I tried like so:
val_dict= {'1/2 pint': 'half', '1': 'one', '5': 'five'}
text = 'I need 1/2 pint of beer'
for x in val_dict:
if x in text:
print(x, val_dict.get(x))
But I'm getting
1/2 pint half
1 one
Instead of only 'half'. How to solve it? '/' is not an escape character as far as I know.
Edit: Given the solutions provided in other topics, I tried regular expressions:
for x in val_dict:
if re.search(rf"\b{x}\b", text, re.IGNORECASE):
print(x + " match")
>>> 1/2 pint match
>>> 1 match
which is ok, because of \\b
but:
for x in val_dict:
if re.search(rf"^{x}$", text, re.IGNORECASE):
print(x + " match")
Should match exact occurrence, but gives no result. Why?
Please note that my dict keys may contain spaces, so splitting the text by spaces won't work.
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.