EX)
import re
nodeDic = {"ABC-3K":"True","TTR":"True"}<br />
address = "ABC-3K and TTR"
result = eval(re.sub(r"\b(\w+)\b", lambda m: nodeDic.get(m.group(1), m.group(1)), address))<br />
print(result)
--->True and True
but I have errors:
Traceback (most recent call last): File
"C:/Users/IT1_807_6/PycharmProjects/choonlog/Test/eval.py", line 6, in
result = eval(re.sub(r"\b(\w+)\b", lambda m: nodeDic.get(m.group(1), m.group(1)), address)) File "", line
1
GSK-3b and True
^ SyntaxError: invalid syntax
When I remove hyphen(-) no matters. But when I use hyphen(-) symbol it matters. I have to use the hyphen(-)
Ok i found a regex that does what you want, but it is a complete mess:
(?:(?<=\A)|(?<=\s))(.+?)(?=\Z|\s)
If you use this regex:
nodeDic = {"ABC-3K":"True","TTR":"True"}
address = "ABC-3K and TTR"
result = eval(re.sub(r"(?:(?<=\A)|(?<=\s))(.+?)(?=\Z|\s)", lambda m: nodeDic.get(m.group(1),m.group(1)), address))
print(result) # prints True
Related
I like to see some meaningful description at assertion failure.
Here is my code and its execution:
>cat /tmp/1.py
a="aaa" + "bbb"
print(a)
assert ("hello" + a) and 0
>python /tmp/1.py
aaabbb
Traceback (most recent call last):
File "/tmp/1.py", line 3, in <module>
assert ("hello" + a) and 0
AssertionError
I am using Python 3.7.
You know why "hello" + a is not evaluated first as a string concatenation? And how can I make it?
[UPDATE] Thanks for all the replies, here is what I am looking for:
>cat /tmp/1.py
a="aaa" + "bbb"
print(a)
assert 0, "hello" + a
According to the docs, the failure message follows a comma:
assert some_condition, "This is the assert failure message".
This is equivalent to:
if __debug__:
if not some_condition:
raise AssertionError("This is the assert failure message")
And as noted in the comments, assert is not a function call. Don't add parenthesis, or you may have odd results. assert(condition, message) will be interpreted as a tuple being used as a condition with no message, and will never fail.
You can add your description just after your assert statement with a comma.
Such as:
assert ("hello" + a) and 0, 'Your description'
The result will be:
aaabbb
Traceback (most recent call last):
File "test.py", line 6, in <module>
assert ("hello" + a) and 0, "Your description"
AssertionError: Your description
This is so far what has been my progress with this regex function :
import os, re
dpath="/root/tree/def/"
fmatch = re.compile(r'\s+''[\[]+''[A-Z]+''[\]]+')
pmatch = fmatch.match('[FLAC]')
def replace(pmatch,df):
m = re.sub(fmatch,df)
print (m)
def regex(dpath):
for df in os.listdir(dpath):
replace(pmatch, df)
regex (dpath)
First do a for loop and look for files in (dpath), then pass the directory name string to replace(). But I am getting missing argument 'string' error :
root#debian:~# python regex3.py
Traceback (most recent call last):
File "regex3.py", line 18, in <module>
regex (dpath)
File "regex3.py", line 16, in regex
replace(pmatch, df)
File "regex3.py", line 9, in replace
m = re.sub(fmatch,df)
TypeError: sub() missing 1 required positional argument: 'string'
It seems that you want to replace alls all matches of the RegEx \s+[\[]+[A-Z]+[\]]+ to [FLAC]
Make sure you do the following:
def replace(pmatch,df):
m = fmatch.sub('[FLAC]', df)
print (m)
Using #martin-konecny 's Example,
I got this that worked.
Create Files for Example
# Run this in your Shell/Terminal
touch /tmp/abc.FLAC
touch /tmp/abcd.FLAC
Run Python
import re
import os
dpath = '/tmp/'
fmatch = re.compile(r'.+\.FLAC')
pmatch = fmatch.match('[FLAC]')
def replace(pmatch, df):
m = fmatch.sub('[REDACTED]', df)
print(m)
def regex(dpath):
for df in os.listdir(dpath):
replace(pmatch, df)
regex(dpath)
Result:
# ...
# [REDACTED]
# [REDACTED]
# ...
Great if you want to run a search and keep a selection of your results secret.
I want to validate a python object thanks to a schema. For this I found the schema framework.
I would like to validate a numeric string:
a = {
'phone_number': '12233'
}
Do you know how can I validate this string thanks to a regex?
At this time, I only know how to perform a string validation:
Schema(str).validate('12')
Schema will call any callables; simply provide a function that uses a regular expression:
import re
pattern = re.compile('^12\d+$')
Schema(And(str, lambda x: pattern.match(x) is not None))
Demo:
>>> import re
>>> from schema import Schema, And
>>> pattern = re.compile('^12\d+$')
>>> s = Schema(And(str, lambda x: pattern.match(x) is not None))
>>> s.validate('123234')
'123234'
>>> s.validate('42')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/venvs/stackoverflow-2.7/lib/python2.7/site-packages/schema.py", line 153, in validate
raise SchemaError([None] + x.autos, [e] + x.errors)
schema.SchemaError: <lambda>('42') should evaluate to True
While I execute the below program with little modification I am getting an error.
import sys,re
match=re.compile(r'aa[0-9]+AB')
while 1 :
line=eval(raw_input('Enter the string to search' 'or' "press 'q' to Quit"))
if line == 'q':
print "you are quit from the program"
break
if match.search(line):
print 'Matched:',line
print pat
print 'found',match.group()
print type(pat)
else:
print "no match"
print type(pat)
Input:
'aa12AB'
O/P:
>>> Matched: aa12AB
<_sre.SRE_Pattern object at 0x02793720>
found
Traceback (most recent call last):
File "C:\Pyth`enter code here`on27\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\thangaraj\Desktop\python program\UK Training program\New to add labtop\regular exp\Script1.py", line 11, in <module>
print 'found',match.group()
AttributeError: '_sre.SRE_Pattern' object has no attribute 'group'
>>>
You have to assign to a match object:
m = match.search(line)
and then:
m.group()
Why are you using eval? You should use match.search (although you should probably rename the variable from match as usually, the return value of search is called a match) and the return value of search will have a group method, as #Birei wrote.
I'm trying to implement an assert function. How can I get the text of the failing condition into the error message? If I have to parse it from the backtrace, can I portably rely on anything about the format of frames?
AssertionError is just like any other exception in python, and assert is a simple statement that is equivalent to
if __debug__:
if not expression: raise AssertionError
or
if __debug__:
if not expression1: raise AssertionError(expression2)
so you can add a second parameter to your assertion to have additional output
from sys import exc_info
from traceback import print_exception
# assertions are simply exceptions in Python
try:
assert False, "assert was false"
except AssertionError:
print_exception(*exc_info())
outputs
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
AssertionError: assert was false
If you're sure the expression to test is secure you could do something like this:
File my_assert.py:
import sys
def my_assert(condition):
caller = sys._getframe(1)
if not eval(condition, caller.f_globals, caller.f_locals):
raise AssertionError(repr(condition) + " on line " +
str(caller.f_lineno) + ' in ' +
caller.f_code.co_name)
File test_my_assert.py:
from my_assert import my_assert
global_var = 42
def test():
local_var = 17
my_assert('local_var*2 < global_var') # OK
my_assert('local_var > global_var')
test()
Output:
Traceback (most recent call last):
File "test_my_assert.py", line 10, in <module>
test()
File "test_my_assert.py", line 8, in test
my_assert('local_var > global_var')
File "my_assert.py", line 8, in my_assert
caller.f_code.co_name)
AssertionError: 'local_var > global_var' on line 8 in test
My very hackish solution:
def my_assert(condition):
if not eval(condition):
# error stuff
Then use it by placing the condition in quotation marks. It is then a string that can be printed in the error message.
Or, if you want it to actually raise an AssertionError:
def my_assert(condition):
if not eval(condition):
raise AssertionError(condition)