I am using
rf['email'].errors
As said in docs, I can use it to have array of errors.
[str(e) for e in rf['email'].errors] #give me ["<django.utils.functional.__proxy__>"]
If repr or str - it gives ul's or string of array.
So it worked only when I used repr and eval together. But I think its stupid solution.
eval(`rf['email'].errors`)
You have a couple options depending on the output you'd like.
Option one, use the unicode constructor to convert the data:
list_of_error_texts = [unicode(e) for e in rf['email'].errors]
(Django's proxy object implements a method that responds to unicode.)
Option two, get the ErrorList as text. This produces a newline separated list of error text, with each line preceded by an asterisk:
print rf['email'].errors.as_text()
* My error one
* My error two
Option three, use django's force_unicode function. This is like unicode, but has some extra safety features:
from django.utils.encoding import force_unicode
list_of_error_texts = [force_unicode(e) for e in rf['email'].errors]
Related
i have recently started building a bot in discord.py and got stuck in this situation here
#client.command()
async def replace(ctx, *, arg):
msg = f"{arg}" .format(ctx.message).replace('happe', '<:happe:869470107066302484>')
await ctx.send(msg)
this is a command which replaces the word "happe" with the emoji so this looks like :
Command : {prefix}replace i am very happe
Result : i am very "emoji for happe"
but i want to make it so we can replace multiple words with different emoji and not just a single one like
Command : {prefix}replace i am not happe, i am sad
Result : i am not "emoji for happe", i am "emoji for sad"
is there a way to edit multiple words in just one sentence like using a json file of making a list of emojis and its id?
also this command doesnt seems to work in cogs and says command is invalid
is there a way to edit multiple words in just one sentence like using a json file ot making a list of emojis and its id?
Yes, you can do just that. Make a list of word-emoji pairs and iterate over all of them to replace every word.
async def replace(ctx, *, arg):
l = [("happe", "<:happe:869470107066302484>"), ("sad", "..."), ...]
msg = arg # Making a copy here to avoid editing the original arg in case you want to use it at some point
for word, emoji in l:
msg = msg.replace(word, emoji)
await ctx.send(msg)
also this command doesnt seems to work in cogs and says command is invalid
In cogs the decorator is #commands.command(), not #client.command(). Don't forget the from discord.ext import commands import to get access to it.
Lastly, I'm a bit confused what f"{arg}" .format(ctx.message) is supposed to be doing? You can remove the .format and the f-string entirely. args is already a string so putting it in an f-string with nothing else has no effect, and .format(ctx.message) doesn't do anything either. The result of that entire thing is the same as just arg.
>>> arg = "this is the arg"
>>> f"{arg}".format("this has no effect")
'this is the arg'
I'm trying to match a given string with nre:
from nre import findIter, re
const sourceString = """
39
00:04:01,116 --> 00:04:01,783
Attrape.
"""
let srtRex = re"\d+\R\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+\R(\w+)"
for m in findIter(sourceString, srtRex, 0):
echo(m.captures[0])
This doesn't compile though, it fails with Error: undeclared field: 'captures' for type nre.RegexMatch [declared in /usr/local/Cellar/nim/1.2.6/nim/lib/impure/nre.nim(149, 3)].
This is weird, because if I do echo(m), I get the raw strings, so the match itself worked fine. It's only this field I can't access. And that is weird, because in this issue the (working) example code is pretty much the same.
Importing whole modules is idiomatic in Nim, and leads to ambiguities rarely, thanks to a strong type system. see https://narimiran.github.io/2019/07/01/nim-import.html for a great rundown on why Nim doesn't share Python's import issues.
However, here's how to do what you want to do, even if it's not idiomatic Nim:
You're using more than just re and findIter, you also use the proc captures, and the [] proc, so your import line needs to be:
from nre import findIter, re, captures, `[]`
or, for complete namespace separation, but quite ugly, you can:
from nre import nil
let srtRex = nre.re"\d+\R\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+\R(\w+)"
for m in nre.findIter(sourceString, srtRex, 0):
echo(nre.`[]`(nre.captures(m),0))
It seems to be the imports. It works with import nre instead of from nre import findIter, re. But why? I want to keep my namespace clean!
i am using
parser = argparse.ArgumentParser()
subparser = parser.add_subparsers()
add_parser = subparsers.add_parser("add", help="Add parser")
add_parser.add_argument("-project", default="global")
edit_parser = subparsers.add_parser("edit", help="Edit parser")
I want to achieve smething like this:
python myprogram.py add
python myprogram.py edit
python myprogram.py "A random string"
Where in the first two usecases my program can asign the right subparser based on the keyword "add" or "edit". I am interested in the last case, where it maps to any random string that i provide.
There isn't a direct way of doing this. The use of subparsers is an extension of a positional argument with choices.
parser.add_argument('cmd', choices=['add', 'edit', ...])
It accepts a string if it is in choices. There isn't a builtin pattern matching mechanism.
I think your simplest solution would be to add one step:
custom = subparser.add_parser('custom', help='give a random string')
custom.add_argument('anystring', help='random quoted string')
python myprogram.py custom 'any random string'
I can imagine writing a custom choices class that could do both kinds of matching. It would require a custom __contains__ method (and maybe a new __iter__ to list choices in the help). But incorporating that into the _SubParsersAction class would require some serious coding.
A few more details. Your subparser object is an _SubParsersAction. Its choices attribute is an OrderedDict. When you add_parser, it creates a new ArgumentParser (the add_parser object), and enters it into the dict with the named key (plus any aliases). When parsing your input, argparse matches the strings against the keys of this dictionary. So, to implement your ideal, you'd have to change this dictionary lookup.
Another option is to look at sys.argv[1:] at the start. If one of your 'cmds' is present call the parser to get the full subparser action. Otherwise handle the inputs yourself, or call another parser that handles 'a random string' as an ordinary positional argument. Sometimes it just isn't worth the effort to twist argparse into a special shape.
I have the following XML file :
<user-login-permission>true</user-login-permission>
<total-matched-record-number>15000</total-matched-record-number>
<total-returned-record-number>15000</total-returned-record-number>
<active-user-records>
<active-user-record>
<active-user-name>username</active-user-name>
<authentication-realm>realm</authentication-realm>
<user-roles>Role</user-roles>
<user-sign-in-time>date</user-sign-in-time>
<events>0</events>
<agent-type>text</agent-type>
<login-node>node</login-node>
</active-user-record>
There are many records
I'm trying to get values from tags and save them in a different text file using the following code :
soup = BeautifulSoup(open("path/to/xmlfile"), features="xml")
with open('path/to/outputfile', 'a') as f:
for i in range(len(soup.findall('active-user-name'))):
f.write ('%s\t%s\t%s\t%s\n' % (soup.findall('active-user-name')[i].text, soup.findall('authentication-realm')[i].text, soup.findall('user-roles')[i].text, soup.findall('login-node')[i].text))
I get the error TypeError : 'NoneType' object not callable Python with BeautifulSoup XML for line : for i in range(len(soup.findall('active-user-name'))):
Any idea what could be causing this?
Thanks!
There are a number of issues that need to be addressed with this, the first is that the XML file you provided is not valid XML - a root element is required.
Try something like this as the XML:
<root>
<user-login-permission>true</user-login-permission>
<total-matched-record-number>15000</total-matched-record-number>
<total-returned-record-number>15000</total-returned-record-number>
<active-user-records>
<active-user-record>
<active-user-name>username</active-user-name>
<authentication-realm>realm</authentication-realm>
<user-roles>Role</user-roles>
<user-sign-in-time>date</user-sign-in-time>
<events>0</events>
<agent-type>text</agent-type>
<login-node>node</login-node>
</active-user-record>
</active-user-records>
</root>
Now onto the python. First off there is not a findall method, it's either findAll or find_all. findAll and find_all are equivalent, as documented here
Next up I would suggest altering your code so you aren't making use of the find_all method quite so often - using find instead will improve the efficiency, especially for large XML files. Additionally the code below is easier to read and debug:
from bs4 import BeautifulSoup
xml_file = open('./path_to_file.xml', 'r')
soup = BeautifulSoup(xml_file, "xml")
with open('./path_to_output_f.txt', 'a') as f:
for s in soup.findAll('active-user-record'):
username = s.find('active-user-name').text
auth = s.find('authentication-realm').text
role = s.find('user-roles').text
node = s.find('login-node').text
f.write("{}\t{}\t{}\t{}\n".format(username, auth, role, node))
Hope this helps. Let me know if you require any further assistance!
The solution is simple: don't use findall method - use find_all.
Why? Because there is no findall method at all, there are findAll and find_all, which are equivalent. See docs for more information.
Though, I agree, error message is confusing.
Hope that helps.
The fix for my version of this problem is to coerce the BeautifulSoup instance into a type string. You do this following:
https://groups.google.com/forum/#!topic/comp.lang.python/ymrea29fMFI
you use the following pythonic:
From python manual
str( [object])
Return a string containing a nicely printable representation of an
object. For strings, this returns the string itself. The difference
with repr(object) is that str(object) does not always attempt to
return a string that is acceptable to eval(); its goal is to return a
printable string. If no argument is given, returns the empty string,
I'm having trouble logging the output of an internationalized django variable.
My application code used the 'message' vaiable OK and it displays
in English and German (the two languages I am working with)
My problem is when I try to make a log of the said 'message' variable output.
I want to log in English and/or German (depending on what the end user is seeing)
I'm using string_concat and it says:
the lazy translations in result will only be converted to strings when result
itself is used in a string (usually at template rendering time).
Here is a code sample:
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import string_concat
message = _('Profile Updated OK')
# Build a log message
fmt_msg = _(message)
log_message = 'Message Sent: '
log_message = string_concat(log_message, fmt_msg)
logger.info(log_message)
The log entry is not translated:
Message Sent: <django.utils.functional.__proxy__ object at 0x9c3c4ac>
Can anyone suggest how I can have the proxy object to be translated
when used with logging?
It's translating OK in my regular Django code just the logging.info() issue.
Cheers!
From the docs:
The result of a ugettext_lazy() call can be used wherever you would use a unicode string (an object with type unicode) in Python. If you try to use it where a bytestring (a str object) is expected, things will not work as expected, since a ugettext_lazy() object doesn't know how to convert itself to a bytestring.
Also, don't call _() twice.
logger.info(u'Message Sent: %s' % message)
You have to force Unicode strings, as documented in http://www.djangobook.com/en/2.0/chapter19/
u"Hello %s" % ugettext_lazy("people")
And do not call the function twice ;)