im having a hard time fixing this one. i have a search function that will look for campaign name or campaign launcher name. for example if a user look for all campaigns launched by john doe. i want to enclose all spaces with '%' (%john%doe%) expected.
campaigns = Campaign.objects.filter(title(re.sub('/\s/g ', '%', search)) | launcher(re.sub('/\s/g ', '%', search)))
i also tried
campaigns = Campaign.objects.filter(title(re.sub(' ', '%', search)) | launcher(re.sub(' ', '%', search)))
but my code is not doing the right thing. im getting
`camp`.`name` LIKE '%john doe%' OR `user`.`name` LIKE '%john doe%'
and if i did the search.replace(" ", "%") im getting
`camp`.`name` LIKE '%john\\%doe%' OR `user`.`name` LIKE '%john\\%doe%'
i also got this sub function
def search_campaign(request, search):
def title(search):
return Q(name__icontains=search)
def launcher(search):
return Q(created_by_name__icontains=search)
any help will be much appreciated.
search.replace(" ", "%") should work for input search = "john doe"
If you want to send the query with % then simply below cod will work for you.
>>> import re
>>> re.sub(" ", "%", " jhon doe ")
'%jhon%doe%'
If you want to send title like %john%doe% for " john doe " then this query should work.
campaigns = Campaign.objects.filter(title(re.sub(' ', '%', search)) | launcher(re.sub(' ', '%', search)))
Correct me if I got something wrong from the question.
"Regex" in python put spaces between words staring with capital letters.
for this first you need to import "re"
import re
def space(input):
i1=re.findall("[a-z][A-Z]*",input)
result=[]
for word in i1:
word=chr(ord(word[])+32)+word[1:]
result.append(word)
print(' '.join(result))
if __name__=="__main__":
input="JohnDoe"
space(input)
Related
I have a paragraph as 'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day. ' .
I want a RegEx for finding 'Hello my name is xyz how may I help you today' and 'have a nice day' in a complete paragraph in a single expression if that could be possible. Between these two phrases which I want to find can be any number of words/sentences.
You can use re.findall to find matching strings. re.findall will return a list with the matches. You can then use an if statement to find if the list is not empty, and thus containing at least one match. Also do not forget to use the re.IGNORECASE, to ignore case sensitive behavior. Below you find an example for both a match and not a match.
import re
txt = 'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day. '
negative_txt = 'Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a terrible day. '
print('for the txt')
my_name_is = re.findall('HeLlO mY nAmE is', txt, flags=re.IGNORECASE)
nice_day = re.findall('have a nice day', txt, flags=re.IGNORECASE)
if my_name_is and nice_day:
print("the sentences 'Hello my name is', and 'have a nice day', are present")
else:
print("the sentence 'Hello my name is' or 'have a nice day', are NOT present")
print('for the negative txt')
my_name_is = re.findall('Hello my name is', negative_txt, flags=re.IGNORECASE)
nice_day = re.findall('have a nice day', negative_txt, flags=re.IGNORECASE)
if my_name_is and nice_day:
print("the sentences 'Hello my name is', and 'have a nice day', are present")
else:
print("the sentence 'Hello my name is' or 'have a nice day', are NOT present")
You can just use the .*, where the . matches any character and the * is the zero-or-more operator.
Hello my name is .* how may I help you today.*have a nice day
Also, I guess you may want to add the IGNORECASE flag to your search.
The final code will be such this:
import re
my_text = "Hello my name is xyz how may I help you today. <SOME MORE SENTNCES HERE> . Thanks for calling have a nice day."
my_regex = r"Hello my name is .* how may I help you today.*have a nice day"
if re.search(my_regex, my_text, re.IGNORECASE) :
print("OK")
I'm looking for a package or any other approach (other than manual replacement) for the templates within string formatting.
I want to achieve something like this (this is just an example so you could get the idea, not the actual working code):
text = "I {what:like,love} {item:pizza,space,science}".format(what=2,item=3)
print(text)
So the output would be:
I love science
How can I achieve this? I have been searching but cannot find anything appropriate. Probably used wrong naming terms.
If there isnt any ready to use package around I would love to read some tips on the starting point to code this myself.
I think using list is sufficient since python lists are persistent
what = ["like","love"]
items = ["pizza","space","science"]
text = "I {} {}".format(what[1],items[2])
print(text)
output:
I love science
My be use a list or a tuple for what and item as both data types preserve insertion order.
what = ['like', 'love']
item = ['pizza', 'space', 'science']
text = "I {what} {item}".format(what=what[1],item=item[2])
print(text) # I like science
or even this is possible.
text = "I {what[1]} {item[2]}".format(what=what, item=item)
print(text) # I like science
Hope this helps!
Why not use a dictionary?
options = {'what': ('like', 'love'), 'item': ('pizza', 'space', 'science')}
print("I " + options['what'][1] + ' ' + options['item'][2])
This returns: "I love science"
Or if you wanted a method to rid yourself of having to reformat to accommodate/remove spaces, then incorporate this into your dictionary structure, like so:
options = {'what': (' like', ' love'), 'item': (' pizza', ' space', ' science'), 'fullstop': '.'}
print("I" + options['what'][0] + options['item'][0] + options['fullstop'])
And this returns: "I like pizza."
Since no one have provided an appropriate answer that answers my question directly, I decided to work on this myself.
I had to use double brackets, because single ones are reserved for the string formatting.
I ended up with the following class:
class ArgTempl:
def __init__(self, _str):
self._str = _str
def format(self, **args):
for k in re.finditer(r"{{(\w+):([\w,]+?)}}", self._str,
flags=re.DOTALL | re.MULTILINE | re.IGNORECASE):
key, replacements = k.groups()
if not key in args:
continue
self._str = self._str.replace(k.group(0), replacements.split(',')[args[key]])
return self._str
This is a primitive, 5 minute written code, therefore lack of checks and so on. It works as expected and can be improved easly.
Tested on Python 2.7 & 3.6~
Usage:
test = "I {{what:like,love}} {{item:pizza,space,science}}"
print(ArgTempl(test).format(what=1, item=2))
> I love science
Thanks for all of the replies.
I have code that looks like this:
import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = str(activity [1:2]) + str(activity [0:1])
print("".join(activity))
I want the output to look like Girl's 9th Basketball, but the current output when printed is
[' Girls 9th']['Basketball ']
I want to get rid of the square brackets. I know I can simply trim it, but I would rather know how to do it right.
You're almost there. When you use .join on a list it creates a string so you can omit that step.
import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = activity[1:2] + activity[0:1]
print(" ".join(activity))
You are stringyfying the lists which is the same as using print(someList) - it is the representation of a list wich puts the [] around it.
import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = activity [1:2] + [" "] + activity [0:1] # reorders and reassignes list
print("".join(activity))
You could consider adding a step:
# remove empty list items and remove trailing/leading strings
cleaned = [x.strip() for x in activity if x.strip() != ""]
print(" ".join(cleaned)) # put a space between each list item
This just resorts the lists and adds the needed space item in between so you output fits.
You can solve it in one line:
new_activity = ' '.join(activity.split(' - ')[::-1])
You can try something like this:
import re
activity = "Basketball - Girls 9th"
activity = re.sub(r'\s', ' ', activity).split('-')
activity = str(activity [1:2][0]).strip() + ' ' + str(activity [0:1][0])
print(activity)
output:
Girls 9th Basketball
I have such a String as an example:
"[greeting] Hello [me] my name is John."
I want to split it and get such a result
('[greetings]', 'Hello' , '[me]', 'my name is John')
Can it be done in one line of code?
OK another example as it seems that many misunderstood the question.
"[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
then I should get
('[greetings]', ' Hello my friends ' , '[me]', ' my name is John. ', '[bow]', ' nice to meet you.')
I basically want to send this kind of string to my robot. It will automatically decompose it and do some motion corresponding to [greetings] [me] and [bow] and in between speak the other strings.
Using regex:
>>> import re
>>> s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
>>> re.findall(r'\[[\w\s.]+\]|[\w\s.]+', s)
['[greeting]', ' Hello my friends ', '[me]', ' my name is John. ', '[bow]', ' nice to meet you.']
Edit:
>>> s = "I can't see you"
>>> re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]
["I can't see you"]
>>> s = "[greeting] Hello my friends [me] my name is John. [bow] nice to meet you."
>>> re.findall(r'\[.*?\]|.*?(?=\[|$)', s)[:-1]
['[greeting]', ' Hello my friends ', '[me]', ' my name is John. ', '[bow]', ' nice to meet you.'
The function you're after is .split(). The function accepts a delimiter as its argument and returns a list made by splitting the string at every occurrence of the delimiter. To split a string, using either "[" or "]" as a delimiter, you should use a regular expression:
import re
str = "[greeting] Hello [me] my name is John."
re.split("\]|\[", str)
# returns ['', 'greeting', ' Hello ', 'me', ' my name is John.']
This uses a regular expression to split the string.
\] # escape the right bracket
| # OR
\[ # escape the left bracket
I think can't be done in one line, you need first split by ], then [:
# Run in the python shell
sentence = "[greeting] Hello [me] my name is John."
for part in sentence.split(']')
part.split('[')
# Output
['', 'greeting']
[' Hello ', 'me']
[' my name is John.']
Let us say I have a string
c = "a string is like this and roberta a a thanks"
I want the output to be as
' string is like this and roberta thanks"
This is what I am trying
c.replace('a', ' ')
' string is like this nd robert thnks'
But this replaces each 'a' in the string
So I tried this
c.replace(' a ', ' ')
'a string is like this and roberta thanks'
But this leaves out 'a' in the starting of the string.
How do i do this?
this looks like a job for re :
import re
while re.subn('(\s+a\s+|^a\s+)',' ',txt)[1]!=0:
txt=re.subn('(\s+a\s+|^a\s+)',' ',txt)[0]
I myself figured it out.
c = "a string is like this and roberta a a thanks"
import re
re.sub('\\ba\\b', ' ', c)
' string is like this and roberta thanks'
Here you go myself! Enjoy!