Re: Printing n elements per line in a list
def perline(n):
count = 1
while 1:
yield (count == n) and "\n" or " "
count = count % n + 1
r = range(1,101)
p = perline(5)
print "".join("%d%s" % (x, p.next()) for x in r)
unexpected wrote:
> If have a list from 1 to 100, what's the easiest, most elegant way to
> print them out, so that there are only n elements per line.
>
> So if n=5, the printed list would look like:
>
> 1 2 3 4 5
> 6 7 8 9 10
> 11 12 13 14 15
> etc.
>
> My search through the previous posts yields methods to print all the
> values of the list on a single line, but that's not what I want. I feel
> like there is an easy, pretty way to do this. I think it's possible to
> hack it up using while loops and some ugly slicing, but hopefully I'm
> missing something
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie needs Help
Also, it may be easier to use string interpolation, as in:
return "INSERT INTO statecode (state, name) VALUES ('%(state)s',
'%(name)s')" % insert_dict
...after all necessary escaping, of course.
John Machin wrote:
> len wrote:
> > Hi all
> >
> > I am writing a python program that inserts records into a database on
> > XP using mxODBC.
> >
> > I need to write a section of code which will create the following SQL
> > command as an example;
> >
> > INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
> >
> > This statement will be built up using the following code;
> >
> > import mx.ODBC
> > import mx.ODBC.Windows
> > def insertFromDict(table, dict):
> > """Take dictionary object dict and produce sql for
> > inserting it into the named table"""
> > sql = 'INSERT INTO ' + table
> > sql += ' ('
> > sql += ', '.join(dict)
> > sql += ') VALUES ('
> > sql += ', '.join(map(dictValuePad, dict)) # ??? this code does
> > NOT format correctly
> > sql += ')'
> > return sql
> >
> > def dictValuePad(key):# ??? this code
> > does Not format correctly
> > return "'" + str(key) + "'"
> >
> > db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
> > c = db.cursor()
> > insert_dict = {'state':'IL', 'name':'Illinois'}
> > sql = insertFromDict("statecode", insert_dict)
> > print sql
> > c.execute(sql)
> >
>
> The code below will do what you say that you want to do -- so long as
> all your columns are strings (varchar or whatever in SQL terms).
> Otherwise IMHO you would be much better off doing it this way:
> sql = "insert into policy (type, premium) values(?, ?)"
> data = ('building', 123.45)
> cursor.execute(sql, data)
> for two reasons:
> (1) let the ODBC kit worry about formatting dates, strings with
> embedded single quotes, etc
> (2) it can be more efficient; the sql is constant and needs to be
> parsed only once
> (3) [bonus extra reason] the way you are doing it is vulnerable to
> what's called an "SQL injection attack"; although you have no doubt
> eyeballed all the data, doing it that way is a bad habit to get into.
>
> You should be able to modify the supplied code very easily to produce
> the sql variety with "?" in it.
>
> HTH,
> John
>
> C:\junk>type sqlinsdict.py
> def sqlquote(astring):
> return "'" + astring.replace("'", "''") + "'"
>
> def insertFromDict(table, adict):
> """Take dictionary object dict and produce sql for
> inserting it into the named table.
> Sample input:
> insert_dict = {'state':'IL', 'name':'Illinois'}
> sql = insertFromDict("statecode", insert_dict)
> Required output:
> INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
> """
>
> t = [
> 'INSERT INTO ',
> table,
> ' (',
> ', '.join(adict.keys()),
> ') VALUES (',
> ', '.join(sqlquote(x) for x in adict.values()),
> ')',
> ]
> return ''.join(t)
>
> if __name__ == "__main__":
> tests = [
> ('IL', 'Illinois'),
> ('OH', "O'Hara"),
> ]
> cols = ['state', 'name']
> for test in tests:
> the_dict = dict(zip(cols, test))
> print the_dict
> print insertFromDict('statecode', the_dict)
>
> C:\junk>sqlinsdict.py
> {'state': 'IL', 'name': 'Illinois'}
> INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
> {'state': 'OH', 'name': "O'Hara"}
> INSERT INTO statecode (state, name) VALUES ('OH', 'O''Hara')
--
http://mail.python.org/mailman/listinfo/python-list
Re: extract certain values from file with re
Can you safely assume that the lines you want to extract all contain
numbers, and that the lines you do not wish to extract do not contain
numbers?
If so, you could just use the Linux grep utility: "grep '[0123456789]'
filename"
Or, in Python:
import re
inf = file("your-filename-here.txt")
outf = file("result-file.txt","w")
digits = re.compile("\d")
for line in inf:
if digits.search(line): outf.write(line)
outf.close()
inf.close()
As for your "more difficult" file, take a look at the CSV module. I
think that by changing the delimiter from a comma to a |, you will be
95% of the way to your goal.
Fabian Braennstroem wrote:
> Hi,
>
> I would like to remove certain lines from a log files. I had
> some sed/awk scripts for this, but now, I want to use python
> with its re module for this task.
>
> Actually, I have two different log files. The first file looks
> like:
>
>...
>'some text'
>...
>
>ITER I- GLOBAL ABSOLUTE RESIDUAL -I
> I FIELD VALUES AT MONITORING LOCATION --I
> NOUMOM VMOM WMOM MASS T EN DISS ENTH
> UVWP TE EDT
> 1 9.70E-02 8.61E-02 9.85E-02 1.00E+00 1.61E+01 7.65E+04 0.00E+00
> 1.04E-01-8.61E-04 3.49E-02 1.38E-03 7.51E-05 1.63E-05 2.00E+01
> 2 3.71E-02 3.07E-02 3.57E-02 1.00E+00 3.58E-01 6.55E-01 0.00E+00
> 1.08E-01-1.96E-03 4.98E-02 7.11E-04 1.70E-04 4.52E-05 2.00E+01
> 3 2.64E-02 1.99E-02 2.40E-02 1.00E+00 1.85E-01 3.75E-01 0.00E+00
> 1.17E-01-3.27E-03 6.07E-02 4.02E-04 4.15E-04 1.38E-04 2.00E+01
> 4 2.18E-02 1.52E-02 1.92E-02 1.00E+00 1.21E-01 2.53E-01 0.00E+00
> 1.23E-01-4.85E-03 6.77E-02 1.96E-05 9.01E-04 3.88E-04 2.00E+01
> 5 1.91E-02 1.27E-02 1.70E-02 1.00E+00 8.99E-02 1.82E-01 0.00E+00
> 1.42E-01-6.61E-03 7.65E-02 1.78E-04 1.70E-03 9.36E-04 2.00E+01
>...
>...
>...
>
> 2997 3.77E-04 2.89E-04 3.05E-04 2.71E-02 5.66E-04 6.28E-04 0.00E+00
> -3.02E-01 3.56E-02-7.97E-02-7.11E-02 4.08E-02 1.86E-01 2.00E+01
> 2998 3.77E-04 2.89E-04 3.05E-04 2.71E-02 5.65E-04 6.26E-04 0.00E+00
> -3.02E-01 3.63E-02-8.01E-02-7.10E-02 4.02E-02 1.83E-01 2.00E+01
> 2999 3.76E-04 2.89E-04 3.05E-04 2.70E-02 5.64E-04 6.26E-04 0.00E+00
> -3.02E-01 3.69E-02-8.04E-02-7.10E-02 3.96E-02 1.81E-01 2.00E+01
> 3000 3.78E-04 2.91E-04 3.07E-04 2.74E-02 5.64E-04 6.26E-04 0.00E+00
> -3.01E-01 3.75E-02-8.07E-02-7.09E-02 3.91E-02 1.78E-01 2.00E+01
> && --
>
>
>
>'some text'
>
>
> I actually want to extract the lines with the numbers, write
> them to a file and finally use gnuplot for plotting them. A
> nicer and more python way would be to extract those numbers,
> write them into an array according to their column and plot
> those using the gnuplot or matplotlib module :-)
>
> Unfortunately, I am pretty new to the re module and tried
> the following so far:
>
>
> import re
> pat = re.compile('\ \ \ NO.*?&&', re.DOTALL)
> print re.sub(pat, '', open('log_star_orig').read())
>
>
> but this works just the other way around, which means that
> the original log file is printed without the number part. So
> the next step would be to delete the part from the first
> line to '\ \ \ \ NO' and the part from '&&' to the end,
> but I do not know how to address the first and last line!?
>
> Would be nice, if you can give me a hint and especially
> interesting would it be, when you have an idea, how I can
> put those columns in arrays, so I can plot them right away!
>
>
> A more difficult log file looks like:
>
> ==
> OUTER LOOP ITERATION =1 CPU SECONDS = 2.40E+01
> --
> | Equation | Rate | RMS Res | Max Res | Linear Solution |
> +--+--+-+-+--+
> | U-Mom| 0.00 | 1.0E-02 | 5.0E-01 | 4.9E-03 OK|
> | V-Mom| 0.00 | 2.4E-14 | 5.6E-13 | 3.8E+09 ok|
> | W-Mom| 0.00 | 2.5E-14 | 8.2E-13 | 8.3E+09 ok|
> | P-Mass | 0.00 | 1.1E-02 | 3.4E-01 | 8.9 2.7E-02 OK|
> +--+--+-+-+--+
> | K-TurbKE | 0.00 | 1.8E+00 | 1.8E+00 | 5.8 2.2E-08 OK|
> | E-Diss.K | 0.00 | 1.9E+00 | 2.0E+00 | 12.4 2.2E-08 OK|
> +--+--+-+-+--+
>
> ==
> OUTER LOOP ITERATION =2 CPU SECONDS = 8.57E+01
> --
> | Equation | Rate | RMS Res | Max Res | Linear Solution |
> +--+
Re: Regular expression worries
You are opening the same file twice, reading its contents line-by-line
into memory, replacing "Document" with "Doc" *in memory*, never writing
that to disk, and then discarding the line you just read into memory.
If your file is short, you could read the entire thing into memory as
one string using the .read() method of fh (your file object). Then,
call .replace on the string, and then write to disk.
If your file is long, then you want to do the replace line by line,
writing as you go to a second file. You can later rename that file to
the original file's name and delete the original.
Also, you aren't using regular expressions at all. You do not
therefore need the re module.
CSUIDL PROGRAMMEr wrote:
> folks
> I am new to python, so excuse me if i am asking stupid questions.
>
> I have a txt file and here are some lines of it
>
> Document Keyword
> Keyword Keyword
> Keyword > Keyword Keyword Keyword
> Keyword Keyword Keyword
> I am writing a python program to replace the tags and word Document
> with Doc.
>
> Here is my python program
>
> #! /usr/local/bin/python
>
> import sys
> import string
> import re
>
> def replace():
> filename='/root/Desktop/project/chatlog_20060819_110043.xml.txt'
> try:
> fh=open(filename,'r')
> except:
> print 'file not opened'
> sys.exit(1)
> for l in
> open('/root/Desktop/project/chatlog_20060819_110043.xml.txt'):
>
> l=l.replace("Document", "DOC")
> fh.close()
>
> if __name__=="__main__":
> replace()
>
> But it does not replace Document with Doc in the txt file
>
> Is there anything wrong i am doing
>
> thanks
--
http://mail.python.org/mailman/listinfo/python-list
Re: Decorators and how they relate to Python - A little insight please!
When you want to repeatedly apply a certain ALGORITHM to arbitrary sets of DATA, you write a FUNCTION. When you want to add a certain BEHAVIOR to arbitrary sets of FUNCTIONS, you write a DECORATOR. An excellent use of decorators is in Django, the web programming framework. Django keeps track of usernames and passwords for you. Occasionally, there are some things on your web site that you only want to only let people who are logged in do (like, say, leave a comment on your blog). Instead of making you begin every such function with "if user_is_logged in:" or some similar abomination, Django lets you just put a @require_login decorator before that function. Pretty spiffy. Jerry wrote: > I have just started to do some semi-serious programming (not one-off > specialized scripts) and am loving Python. I just seem to get most of > the concepts, the structure, and the classes (something I struggled > with before in other languages). I've seen many concepts on the web > (i.e. stacks, queues, linked lists) and can usually understand them > pretty well (event if I don't always know when to use them). Now I've > come accross decorators and even though I've read the PEP and a little > in the documentation, I just don't get what they are or what problem > they are trying to solve. Can anyone please point me to a general > discussion of decorators (preferrably explained with Python)? > > Thanks, > Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: why does this unpacking work
It's just sequence unpacking. Did you know that this works?:
pair = ("California","San Francisco")
state, city = pair
print city
# 'San Francisco'
print state
# 'California'
John Salerno wrote:
> I'm a little confused, but I'm sure this is something trivial. I'm
> confused about why this works:
>
> >>> t = (('hello', 'goodbye'),
> ('more', 'less'),
> ('something', 'nothing'),
> ('good', 'bad'))
> >>> t
> (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'),
> ('good', 'bad'))
> >>> for x in t:
> print x
>
>
> ('hello', 'goodbye')
> ('more', 'less')
> ('something', 'nothing')
> ('good', 'bad')
> >>> for x,y in t:
> print x,y
>
>
> hello goodbye
> more less
> something nothing
> good bad
> >>>
>
> I understand that t returns a single tuple that contains other tuples.
> Then 'for x in t' returns the nested tuples themselves.
>
> But what I don't understand is why you can use 'for x,y in t' when t
> really only returns one thing. I see that this works, but I can't quite
> conceptualize how. I thought 'for x,y in t' would only work if t
> returned a two-tuple, which it doesn't.
>
> What seems to be happening is that 'for x,y in t' is acting like:
>
> for x in t:
> for y,z in x:
> #then it does it correctly
>
> But if so, why is this? It doesn't seem like very intuitive behavior.
>
> Thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python and CMS
For a free out of the box solution, look at MoinMoin. It is wiki software, but nothing stops you from turning off user signups, locking down the whole site, and just using it as a CMS. It's very easy to set up, can run as a CGI, and requires no database backend. Echo wrote: > I am going to start working on a church website. And since I like > python, I decided to use WSGI. However, I later found out about all > the different CMS's in php. So I wondered if there where any in > python. > > Sadly, I only found Plone, skeletonz, and PyLucid (If there is any > more, please let me know). Of those three, only PyLucid supports WSGI > and it didn't look very nice to me. > Both Plone and skeletonz looked very nice. However, they can't be > hosted on a regular web host(at least to my knowledge) since they run > as the web server themselves. So hosting would cost more, at least 2-3 > times more from what I've seen. > > So I'm thinking of making a python CMS based on WSGI. I'm now trying > to figure out a few things like the best way to store the content and > how to manage/use plugins. For storing the content, the only ways I > know of are as files or in a database. But I'm not sure what would be > better. And as for how to do plugings, I plan on looking at Plone and > skeletonz. > > As for working with WSGI, I have found > Colubrid(http://wsgiarea.pocoo.org/colubrid/) and > Paste(http://pythonpaste.org/). I was wondering if anyone knew of any > other libraries that make working with WSGI easier. Also, I wondering > if anyone would like to share their experiences of working with those. > > > ps. I know that this is a big and complicated project. But no matter > how far I get, it will be fun because its Python:) > > -- > "Now that I am a Christian I do not have moods in which the whole > thing looks very improbable: but when I was an atheist I had moods in > which Christianity looked terribly probable." > -C. S. Lewis > > -Echo -- http://mail.python.org/mailman/listinfo/python-list
Cross-site scripting (XSS) defense
Is there a module (or, better yet, sample code) that scrubs user-entered text to remove cross-site scripting attacks, while also allowing a small subset of HTML through? Contemplated application: a message board that allows people to use , , and so on, but does not allow any javascript, vbscript, or other nasties. -- http://mail.python.org/mailman/listinfo/python-list
Re: hard to explain for a french ;-)
How about an effort to "compile" Python into JavaScript? Such an effort is underway for Scheme. http://www-sop.inria.fr/mimosa/personnel/Florian.Loitsch/scheme2js/ Tim Chase wrote: > > As explained in this thread > > http://mail.python.org/pipermail/python-list/2006-June/348241.html > > what you try to do will never work because your attempts are > > at using python on the client side and only javascript works > > for that purpose. > > Sounds like an opportunity to write JSPython...written in > JavaScript, akin to CPython (written in C), Jython (written in > Java), and PyPy (written in Python)...for those sick enough to > undertake such a freakish task... :) > > > No...that wouldn't be slow... > > > -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: string replace
Check out the .translate method and the string.maketrans documentation.
You can use it to delete a list of characters all in one line:
>>> s = "I am the walrus"
>>> import string
>>> s.translate(string.maketrans("",""),"aeiou")
'I m th wlrs'
Michele Petrazzo wrote:
> Hi,
> a lot of times I need to replace more than one char into a string, so I
> have to do something like
>
> value = "test"
> chars = "e"
> for c in chars:
>value = value.replace(c, "")
>
> A solution could be that "replace" accept a tuple/list of chars, like
> that was add into the new 2.5 for startswith.
>
> I don't know, but can be this feature included into a future python release?
>
> Thanks,
> Michele
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python framework questions
mp wrote:
> Hello, I have a couple general questions.
>
> First, how do most web frameworks serve html? I'm coding in python and
> I want to keep all my html seperate from my python stuff. I can serve
> these html files from a mysql database or just from the file system, do
> people use both these options? Are there other options?
The basic idea of templates is that you write something like:
{{ HEADLINE }}
by {{ AUTHOR }}
{{ STORY }}
and the web framework fills in the blanks. No need to store templates
in a SQL database; they are just files.
>
> Second, is a cgi-bin directory really necessary? Are there security
> issues with configuring Apache to allow cgi-bin execution in other
> directories?
Not only unnecessary but unadvisable. It's very 1995, quite out of
fashion now. Read Tim Berners-Lee's article on "Cool URIs." URIs
should just describe content. They are for the user's benefit, not
yours. They are not a place to remind yourself where you stored code,
or what language you write in (hello, .php, .asp, .pl, and .py), or how
your web server gateways with your code.
--
http://mail.python.org/mailman/listinfo/python-list
Copyright lawyer advises "be careful" using Python?
I was scanning the 9/13/2006 issue of the "Electronic Commerce & Law Report," which is a newsletter for lawyers published by BNA. They have an article headlined "Game Developers Making Tomorrow's Hits Face Host of Copyright Issues Along the Way," and the article is mostly a writeup of a speech given by Paul Tauger, identified as "an IP attorney with Schnader Harrison Segal & Lewis LLP, San Francisco." It contains this final paragraph: "Be Careful Using Open Source Tools. Game developers are under constant pressure to deliver games under tight deadlines. Open source software tools can help speed the development process, but may carry with them certain legal risks, Tauger explained. One open source tool popular with the game development community is Python. Unfortunately, the Python Software Foundation's license agreement leaves a lot of unanswered questions about the origin and precise ownership of the tool's code. The license refers to six separate entities that, at one point or another, contributed to the tool's development. PSF's license disclaims any warranties of non-infringement and disavows any indemnification obligation. In theory, if some aspect of Python was deemed to infringe copyrighted code, it could create legal headaches for game developers who rely upon the tool to build certain parts of their games. 'Be aware of the risks attendant,' Tauger said." (page 914) What is our response? Is the PSF that much different from any other open source license? Can anyone identify everyone who ever contributed to the Linux source code? Does ANY free "tool" indemnify people? In fact, does Microsoft indemnify Visual Studio users against the risk that one day the BASIC language will be found to have been infringing a patent all along? -- http://mail.python.org/mailman/listinfo/python-list
Re: iterator question
def transform(seq, size): i = 0 while i < len(seq): yield tuple(seq[i:i+size]) i += size Neal Becker wrote: > Any suggestions for transforming the sequence: > > [1, 2, 3, 4...] > Where 1,2,3.. are it the ith item in an arbitrary sequence > > into a succession of tuples: > > [(1, 2), (3, 4)...] > > In other words, given a seq and an integer that specifies the size of tuple > to return, then for example: > > seq = [a,b,c,d,e,f] > for e in transform (seq, 2): > print e > > would return > (a,b) > (c,d) > (e,f) -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting device addresses into parts
This may be a rare case where regular expressions are not a horrible,
self-defeating idea. Something like:
delimiter = re.compile("[:\.]")
delimiter.split("PCI:2:3.0")
...and then ignore the first entry, and map int the rest.
Alternatively, if the delimiters can really be anything, and if there
are no numbers in the first space ("PCI"), then maybe this approach:
number = re.compile("\d+?")
number.findall("PCI:2:3.0")
Fabian Steiner wrote:
> Bruno Desthuilliers wrote:
> > Fabian Steiner wrote:
> >> I often have to deal with strings like "PCI:2:3.0" or "PCI:3.4:0" and
> >> need the single numbers as tuple (2, 3, 0) or (3, 4, 0). Is there any
> >> simple way to achieve this? So far I am using regular expressions but I
> >> would like to avoid them ...
> >
> > devices = ["PCI:2:3.0", "PCI:3.4:0"]
> > for d in device:
> > nums = tuple(map(int, d.split(':')[1:]))
> > print "for ", d, " : ", nums
>
> Unfortunately, this doesn't work (even if I correct your typos) since
> the delimeter isn't necessary a colon - that's exactly the difficulty I
> am trying to solve.
>
> Regards,
> Fabian Steiner
--
http://mail.python.org/mailman/listinfo/python-list
Re: Query regarding grep!!
You could also use itertools:
import itertools
import re
find = re.compile("pattern")
for line in itertools.ifilter(lambda x: find.search(x),
file(filepath)):
print line
Fredrik Lundh wrote:
> bhavya sg wrote:
>
> > I saw in PEP4 of python 2.5 that grep module has gone
> > obsolete in perl 2.5. But I am not able to find an
> > alternative for that.
>
> the grep module has been deprecated for ages (it's been in the lib-old
> non-standard library since at least Python 2.1). The old grep module
> depends on the regex module, which has been deprecated since Python 1.6,
> and which was finally removed in Python 2.5.
>
> > My doubt is "are the other forms of grep like egrep and ggrep be used
> > instead"?
>
> there are no such modules in Python, afaik.
>
> (and that's a question, not a doubt, right?)
>
> if you have Python code that uses the grep module, you can replace it
> with something like:
>
> import re
>
> def simple_grep(filename, pattern):
> find = re.compile(pattern).search
> for index, line in open(filename):
> if find(line):
> print filename, index, line[:-1]
>
> where pattern is an RE-style pattern, not a REGEX-style pattern (see the
> RE documentation for details).
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Reading a file using a UNC - help!
You should use os.path.exists to test if a file exists. Your
exception-catching structure is not necessary.
Also, if the file you are reading from contains proper Windows
filenames, it is not necessary to replace \ with \\ and so forth. The
\ acts as an escape character only when it is in Python source code,
not when it is in a string read from the real world.
Also, because you wisely use "for x in inputfiles:" it is not necessary
to search for and replace newlines.
[EMAIL PROTECTED] wrote:
> I have the simplest need...to read a file full of file names(unc) and
> then check to see if each of these files exists. I tried with the
> following program, but always get file not found, even when it is
> there. If I type in the file name as a literal it works...
>
> Little program:
>
> #This module checks for file existence
> import string
> import sys
>
> def MainProcess():
>
> fileList = "c:\a_list_of_filenames.txt"
> inputFiles = open(fileList,"r")
>
> cnt = 0
> cntNotFound = 0
>
> for x in inputFiles:
> cnt = cnt + 1
> try:
> x = x.replace("\\","")
> x = x.replace("\n","")
> open(x,"rb")
> #open('myserver\\myshare\\myfile.dat',"r") #works when
> hard coded like this
> except IOError, (errno, strerror):
> print "I/O error(%s): %s" % (errno, strerror)
> cntNotFound = cntNotFound + 1
> print x + " Not Found"
> except ValueError, (errno,strerror):
> print "Some other error! " + str(errno) + " " + strerror
> else:
> print "Found " + x
>
> print str(cnt) + " total..."
> print str(cntNotFound) + " not found..."
>
> if __name__ == '__main__':
> MainProcess()
>
> Many thanks to anyone in advance to can tell me what I am doing wrong!
> Platform is XP with PythonWin.
>
> Richard Kessler
> [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Ruby/Python/REXX as a MUCK scripting language
Have you considered JavaScript Spidermonkey or JavaScript Rhino? Sandboxing is automatic, and lots of people know the language already (although fewer people are familiar with its dynamic object-oriented capabilities). Tony Belding wrote: > I'm interested in using an off-the-shelf interpreted language as a > user-accessible scripting language for a MUCK. I'm just not sure if I > can find one that does everything I need. The MUCK must be able to > call the interpreter and execute scripts with it, but the interpreter > must also be able to call functions in the MUCK code. And then there's > the security issue that really worries me. . . I have to be able to > limit what the interpreter can execute. I can't have my users running > scripts that access the console, access the filesystem or sockets > directly, or call libraries or other binaries outside the MUCK. > > Is this practical? I'm thinking of Ruby or Python for this, if they > can meet the requirements. > > I might even consider REXX. . . I remember ARexx from my Amiga days, > and how great it was for string manipulation and application scripting. > However. . . My immediate target platform, Mac OS X, comes with Ruby > and Python but not REXX, so that's a disadvantage. > > My final option would be to create my own language interpeter where I > have control over everything that happens. That is what MUCKs have > always done in the past. But the result was always quirky, limited > languages like MUF (Multi-User Forth) which really turn off a lot of > coders. Furthermore, I've never created a language before, and it > would be a lot of extra work for me. > > -- > Tony Belding, Hamilton Texas -- http://mail.python.org/mailman/listinfo/python-list
Re: a quickie: range - x
(x for x in xrange(N+1) if x != m) rjtucke wrote: > I want an iterable from 0 to N except for element m (<=M). > I could write > x = range(N) > x.remove(m) > but I want it in one expression. > > Thanks, > Ross -- http://mail.python.org/mailman/listinfo/python-list
Re: What am I supposed to do with an egg?!
Type "sudo easy_install myeggfile.egg." If that gives you an error, then you don't have easy_install installed. Install it this way: sudo apt-get install python-setuptools On Dec 19, 3:44 pm, Morpheus <[EMAIL PROTECTED]> wrote: > On Windows I'm used to install packages by setup.py install. So did I with > Fibranet nanothreads - a few seconds and it was installed. > > On Linux (ubuntu 6.06) all I could get at is an egg file. I found out that > I have to exec easy_install, which didn't much help here (seems to me, at > least - sorry, Linux newbie). > > So, what am I supposed to do here now? > > Kind regards > Morpheus -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp
You want re.sub("(?s)", "", htmldata)
Explanation: To make the dot match all characters, including newlines,
you need to set the DOTALL flag. You can set the flag using the (?_)
syntax, which is explained in section 4.2.1 of the Python Library
Reference.
A more readable way to do this is:
obj = re.compile("", re.DOTALL)
re.sub("", htmldata)
On Dec 19, 3:59 pm, vertigo <[EMAIL PROTECTED]> wrote:
> Hello
>
>
>
>
>
> > On Tuesday 19 December 2006 13:15, vertigo wrote:
> >> Hello
>
> >> I need to use some regular expressions for more than one line.
> >> And i would like to use some modificators like: /m or /s in perl.
> >> For example:
> >> re.sub(".*","",data)
>
> >> will not cut out all javascript code if it's spread on many lines.
> >> I could use something like /s from perl which treats . as all signs
> >> (including new line). How can i do that ?
>
> >> Maybe there is other way to achieve the same results ?
>
> >> Thanx
>
> > Take a look at Chapter 8 of 'Dive Into Python.'
> >http://diveintopython.org/toc/index.htmli read whole regexp chapter - but
> >there was no solution for my problem.
> Example:
>
> re.sub("","",htmldata)
> would remove only comments which are in one line.
> If comment is in many lines like this:
>
>
> it would not work. It's because '.' sign does not matches '\n' sign.
>
> Does anybody knows solution for this particular problem ?
>
> Thanx- Hide quoted text -- Show quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Re: regexp
Oops, I mean obj.sub("", htmldata)
On Dec 19, 4:15 pm, [EMAIL PROTECTED] wrote:
> You want re.sub("(?s)", "", htmldata)
>
> Explanation: To make the dot match all characters, including newlines,
> you need to set the DOTALL flag. You can set the flag using the (?_)
> syntax, which is explained in section 4.2.1 of the Python Library
> Reference.
>
> A more readable way to do this is:
>
> obj = re.compile("", re.DOTALL)
> re.sub("", htmldata)
>
> On Dec 19, 3:59 pm, vertigo <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hello
>
> > > On Tuesday 19 December 2006 13:15, vertigo wrote:
> > >> Hello
>
> > >> I need to use some regular expressions for more than one line.
> > >> And i would like to use some modificators like: /m or /s in perl.
> > >> For example:
> > >> re.sub(".*","",data)
>
> > >> will not cut out all javascript code if it's spread on many lines.
> > >> I could use something like /s from perl which treats . as all signs
> > >> (including new line). How can i do that ?
>
> > >> Maybe there is other way to achieve the same results ?
>
> > >> Thanx
>
> > > Take a look at Chapter 8 of 'Dive Into Python.'
> > >http://diveintopython.org/toc/index.htmliread whole regexp chapter - but
> > >there was no solution for my problem.
> > Example:
>
> > re.sub("","",htmldata)
> > would remove only comments which are in one line.
> > If comment is in many lines like this:
> >
>
> > it would not work. It's because '.' sign does not matches '\n' sign.
>
> > Does anybody knows solution for this particular problem ?
>
> > Thanx- Hide quoted text -- Show quoted text -- Hide quoted text -- Show
> > quoted text -
--
http://mail.python.org/mailman/listinfo/python-list
Re: regexp
Not just Python, but every Regex engine works this way. You want a ?
after your *, as in <--(.*?)--> if you want it to catch the first
available "-->".
At this point in your adventure, you might be wondering whether regular
expressions are more trouble than they are worth. They are. There are
two libraries you need to take a look at, and soon: BeautifulSoup for
parsing HTML, and PyParsing for parsing everything else. Take the time
you were planning to spend on deciphering regexes like
"(\d{1,3}\.){3}\d{1,3}" and spend it learning the basics of those
libraries instead -- you will not regret it.
On Dec 19, 4:39 pm, vertigo <[EMAIL PROTECTED]> wrote:
> Hello
>
> Thanx for help, i have one more question:
>
> i noticed that while matching regexp python tries to match as wide as it's
> possible,
> for example:
> re.sub("","",htmldata)
> would cut out everything before first "" in the
> document.
> Can i force re to math as narrow as possible ?
> (to match first "" after the "
Re: perl better than python for users with disabilities?
Blind programmers can use braille displays, which let them perceive
indentation as easily as sighted programmers can. http://xrl.us/tydj
As for people with physical disabilities that have trouble typing, a
Python-aware editor does the identation for you, so all you have to do
is type a colon and an enter, then a backspace when you are done being
indented.
But it's an interesting question, and I'd like to hear from blind
programmers about how program language design can make their lives
easier or more difficult.
On Dec 20, 11:11 am, Dan Jacobson <[EMAIL PROTECTED]> wrote:
> Can I feel even better about using perl vs. python, as apparently
> python's dependence of formatting, indentation, etc. vs. perl's
> "(){};" etc. makes writing python programs perhaps very device
> dependent. Whereas perl can be written on a tiny tiny screen, and can
> withstand all kinds of users with various disabilities, etc.?
> Also perl is easier to squeeze into makefiles.
--
http://mail.python.org/mailman/listinfo/python-list
Re: error with IDLE on debian
Just a guess, but I think you need to be using at least Python 2.4 if you are going to use IDLE version 2.4.4-2. On Dec 20, 1:16 pm, altern <[EMAIL PROTECTED]> wrote: > Hi > > when i try to run IDLE on my debian laptop I get this error. > > $ idle > Traceback (most recent call last): >File "/usr/bin/idle", line 5, in ? > main() >File "idlelib/PyShell.py", line 1359, in main >File "idlelib/FileList.py", line 44, in new >File "idlelib/PyShell.py", line 105, in __init__ >File "idlelib/EditorWindow.py", line 111, in __init__ >File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 2764, in __init__ > Widget.__init__(self, master, 'text', cnf, kw) >File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1865, in __init__ > self.tk.call( > _tkinter.TclError: expected integer but got "`100" > > I am not sure about what could cause the problem because I didnt use my > laptop for python programming for couple of weeks. Before that it worked > fine. And on that period i might have installed few things. > > I am running Debian unstable with python 2.2.4, tcl8.4, tk8.4, python-tk > 24.4-1 and IDLE 2.4.4-2. I already tried to reinstall IDLE, tk and tcl > and python-tk but that did not solve anything, i keep getting the same > error. > > any ideas? > > thanks > > enrike -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression fun. Repeated matching of a group Q
There's more to re than just sub. How about:
sanesplit = re.split(r"||", text)
date = sanesplit[1]
times = times = [time for time in sanesplit if re.match("\d\d:\d\d",
time)]
... then "date" contains the date at the beginning of the line and
"times" contains all your times.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression fun. Repeated matching of a group Q
You can check len(sanesplit) to see how big your list is. If it is <
2, then there were no 's, so move on to the next line.
It is probably possible to do the whole thing with a regular
expression. It is probably not wise to do so. Regular expressions are
difficult to read, and, as you discovered, difficult to program and
debug. In many cases, Python code that relies on regular expressions
for lots of program logic runs slower than code that uses normal
Python.
Suppose "words" contains all the words in English. Compare these two
lines:
foobarwords1 = [x for x in words if re.search("foo|bar", x) ]
foobarwords2 = [x for x in words if "foo" in x or "bar" in x ]
I haven't tested this with 2.4, but as of a few years ago it was a safe
bet that foobarwords2 will be calculated much, much faster. Also, I
think you will agree, foobarwords2 is a lot easier to read.
--
http://mail.python.org/mailman/listinfo/python-list
Re: how do I factor a number down to one digit?
Your tools are: 1. "map" lets you apply a function to every element of a list. Strings are lists. (List comprehensions let you do the same thing, but "map" is better to use if you are turning in homework). 2. "sum" lets you calculate the sum of all numbers in a list. 3. "val" and "str" let you turn strings into numbers and numbers into strings The only missing piece is a function that turns a letter into a number. It shouldn't be that hard to write one. -- http://mail.python.org/mailman/listinfo/python-list
Re: comple list slices
Python lets you iterate through a list using an integer index, too,
although if you do so we will make fun of you. You can accomplish it
with a while loop, as in:
i = 0
while i < len(rows):
if rows[i] == "This code looks like BASIC without the WEND, doesn't
it?":
rowgroups.append("Pretty much.")
i += 1 # or i += rowspan, whatever.
Do not try to do this with a for loop. In Python, "for i in xrange(5)"
is more like a "foreach $i ( {0,1,2,3,4,5})" in Perl, so changing i in
the loop will not change the value of i on the next loop iteration.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Vectorization and Numeric (Newbie)
"map" takes a function and a list, applies the function to each item in a list, and returns the result list. For example: >>> def f(x): return x + 4 >>> numbers = [4, 8, 15, 16, 23, 42] >>> map(f, numbers) [8, 12, 19, 20, 27, 46] So, rather that ask if there is a different way to write f, I'd just use f in a different way. Another way to accomplish the same result is with a list comprehension: >>> [f(x) for x in numbers] [8, 12, 19, 20, 27, 46] As you can see, if you wanted to "calculate all the values from 1 to n," you could also use these techniques instead of a loop. >>> n = 10 >>> [f(x) for x in xrange(1, n+1)] [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] -- http://mail.python.org/mailman/listinfo/python-list
Re: comple list slices
Although I don't know if this is faster or more efficient than your current solution, it does look cooler: def grouprows(inrows): rows = [] rows[:] = inrows # makes a copy because we're going to be deleting while len(rows) > 0: rowspan = rows[0]["rowspan"] yield rows[0:rowspan] # "returns" this value, but control flow unaffected del rows[0:rowspan] # remove what we just returned from the list, and loop grouper = grouprows(copyrows) print [x for x in grouper] This is basically just a simple function that rips chunks off the front of a list and returns them. Because the function uses "yield" rather than "return," it becomes a generator, which can be treated by Python as an iterator. -- http://mail.python.org/mailman/listinfo/python-list
Re: comple list slices
You don't need to copy the list; but if you don't, your original list will be emptied. Len(rows) recalculates each time the while loop begins. Now that I think of it, "rows != []" is faster than "len(rows) > 0." By the way, you can also do this using (gasp) a control index: def grouprows(rows): index = 0 while len(rows) > index: rowspan = rows[index]["rowspan"] yield rows[index:rowspan + index] index += rowspan ...which kind of brings us back to where we started. -- http://mail.python.org/mailman/listinfo/python-list
Re: Rounding up to the nearest exact logarithmic decade
I like Fredrik's solution. If for some reason you are afraid of logarithms, you could also do: >>> x = 4978 >>> decades = [10 ** n for n in xrange(-1,8)] >>> import itertools >>> itertools.ifilter(lambda decade: x < decade, decades).next() 1 BTW, are the python-dev guys aware that 10 ** -1 = 0.10001 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for uniqness in a list of data
You can come quite close to what you want without splitting the string
at all. It sounds like you are asking the user to build up a string,
and you want to keep checking through your list to find any items that
begin with the string built up by the user. Try something like this:
mylist = ['1p2m_3.3-1.8v_sal_ms','1p2m_3.3-1.8_sal_log']
sofar = ""
loop = True
while loop:
selections = [ x[len(sofar):x.index("_", len(sofar) + 1)]
for x in mylist if x.startswith(sofar) ]
loop = len(selections) > 1
if loop:
print selections
sofar += raw_input("Pick one of those: ")
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help - just a few lines of code needed
There is some fine permutation code in the cookbook. Take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 . You can easily code something like: # xcombinations from the cookbook def xcombinations(items, n): if n==0: yield [] else: for i in xrange(len(items)): for cc in xcombinations(items[:i]+items[i+1:],n-1): yield [items[i]]+cc wordlist = ['HOUSE','jolly','---','0&','99'] for i in xrange(1, len(wordlist)+1): for g in xcombinations(wordlist, i): print "".join(g) > Unfortunately I am not able to program it myself, so > I would appreciate if someone could write this piece of > software, compile it (for DOS or Windows) and send the .exe file to: > > lory88 at gmail . com Meet us halfway, here. At least install Python. Also, it's a dangerous world out there. Don't run .exe s sent to you by people you don't know. -- http://mail.python.org/mailman/listinfo/python-list
Re: scanning for numerals / letters
First, note that form["date"] is all you need. form["date"].value is redundant. I would do this with sets: import string if set(form["date"]) & set(string.ascii_letters) != set([]): print "You have to enter a date with numbers" if set(form["purchases"]) & set(string.digits) != set([]): print "Please do not use numbers" Sets take time to construct, but they test membership faster than strings. Plus, the code just reads logically. (The &, if you couldn't figure it out, does an intersection of sets. You could also use the .intersection method for even better readability). -- http://mail.python.org/mailman/listinfo/python-list
Re: local greediness ???
How about using the numbers as delimiters:
>>> pat = re.compile(r"[\d\.\-]+")
>>> pat.split("[(some text)2.3(more text)4.5(more text here)]")
['[(some text)', '(more text)', '(more text here)]']
>>> pat.findall("[(some text)2.3(more text)4.5(more text here)]")
['2.3', '4.5']
>>> pat.split("[(xxx)11.0(bbb\))8.9(end here)] ")
['[(xxx)', '(bbb\\))', '(end here)] ']
>>> pat.findall("[(xxx)11.0(bbb\))8.9(end here)] ")
['11.0', '8.9']
[EMAIL PROTECTED] wrote:
> hi, all. I need to process a file with the following format:
> $ cat sample
> [(some text)2.3(more text)4.5(more text here)]
> [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)]
> [(xxx)11.0(bbb\))8.9(end here)]
> ...
>
> my goal here is for each line, extract every '(.*)' (including the
> round
> brackets, put them in a list, and extract every float on the same line
> and put them in a list.. here is my code:
>
> p = re.compile(r'\[.*\]$')
> num = re.compile(r'[-\d]+[.\d]*')
> brac = re.compile(r'\(.*?\)')
>
> for line in ifp:
> if p.match(line):
> x = num.findall(line)
> y = brac.findall(line)
> print x, y len(x), len(y)
>
> Now, this works for most of the lines. however, I'm having problems
> with
> lines such as line 3 above (in the sample file). here, (bbb\)) contains
> an escaped
> ')' and the re I use will match it (because of the non-greedy '?'). But
> I want this to
> be ignored since it's escaped. is there a such thing as local
> greediness??
> Can anyone suggest a way to deal with this here..
> thanks.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression help
If you are parsing HTML, it may make more sense to use a package designed especially for that purpose, like Beautiful Soup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expression help
If what you need is "simple," regular expressions are almost never the
answer. And how simple can it be if you are posting here? :)
BeautifulSoup isn't all that hard. Observe:
>>> from BeautifulSoup import BeautifulSoup
>>> html = '10:00am - 11:00am: >> href="/tvpdb?d=tvp&id=167540528&[snip]>The Price Is Right'
>>> soup = BeautifulSoup(html)
>>> soup('a')
[ThePrice Is Right]
>>> for show in soup('a'):
print show.contents[0]
The Price Is Right
RunLevelZero wrote:
> I considered that but what I need is simple and I don't want to use
> another library for something so simple but thank you. Plus I don't
> understand them all that well :)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Gettings subdirectories
It's a bit overkill, but consider using os.walk. root, dirnames, filenames = os.walk(r"C:\").next() # (in real code, you'd want to catch exceptions here) print dirnames Florian Lindner wrote: > Hello, > how can I get all subdirectories of a given directories? os.listdir() gives > me all entries and I've found no way to tell if an object is a file or a > directory. > > Thanks, > > Florian -- http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Use __repr__. Behold:
>>> class NamedThing(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
>>> a = NamedThing("Delaware")
>>> b = NamedThing("Hawaii")
>>> d = {}
>>> d[a] = 1
>>> d[b] = 50
>>> print d
{Delaware: 1, Hawaii: 50}
>>> d[a]
1
>>> d[b]
50
Although this is a bit illegal, because repr is not supposed to be used
this way.
Joel Hedlund wrote:
> Hi!
>
> There's one thing about dictionaries and __hash__() methods that puzzle me. I
> have a class with several data members, one of which is 'name' (a str). I
> would
> like to store several of these objects in a dict for quick access
> ({name:object} style). Now, I was thinking that given a list of objects I
> might
> do something like
>
> d = {}
> for o in objects:
> d[o] = o
>
> and still be able to retrieve the data like so:
>
> d[name]
>
> if I just defined a __hash__ method like so:
>
> def __hash__(self):
> return self.name.__hash__()
>
> but this fails miserably. Feel free to laugh if you feel like it. I cooked up
> a
> little example with sample output below if you care to take the time.
>
> Code:
> ---
> class NamedThing(object):
> def __init__(self, name):
> self.name = name
> def __hash__(self):
> return self.name.__hash__()
> def __repr__(self):
> return ''
> name = 'moo'
> o = NamedThing(name)
> print "This output puzzles me:"
> d = {}
> d[o] = o
> d[name] = o
> print d
> print
> print "If I wrap all keys in hash() calls I'm fine:"
> d = {}
> d[hash(o)] = o
> d[hash(name)] = o
> print d
> print
> print "But how come the first method didn't work?"
> ---
>
> Output:
> ---
> This output puzzles me:
> {'moo': , : }
>
> If I wrap all keys in hash() calls I'm fine:
> {2038943316: }
>
> But how come the first method didn't work?
> ---
>
> I'd be grateful if anyone can shed a litte light on this, or point me to some
> docs I might have missed.
>
> Also:
> Am I in fact abusing the __hash__() method? If so - what's the intended use of
> the __hash__() method?
>
> Is there a better way of implementing this?
>
> I realise I could just write
>
> d[o.name] = o
>
> but this problem seems to pop up every now and then and I'm curious if there's
> some neat syntactic trick that I could legally apply here.
>
> Thanks for your time!
> /Joel Hedlund
--
http://mail.python.org/mailman/listinfo/python-list
Re: Possibly dumb question about dicts and __hash__()
Actually, come to think of it, __str__ works just as well.
>>> class NamedThing(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
>>> d = {}
>>> d[a] = 1
>>> d[b] = 50
>>> d
{<__main__.NamedThing object at 0x00C528D0>: 1, <__main__.NamedThing
object at 0x00C529B0>: 50}
>>> d[a]
1
>>> d[b]
50
This is what you should use, instead of my first answer. From the docs
for __repr__: "If at all possible, this should look like a valid Python
expression that could be used to recreate an object with the same value
(given an appropriate environment). If this is not possible, a string
of the form "<...some useful description...>" should be returned. ...
This is typically used for debugging, so it is important that the
representation is information-rich and unambiguous."
[EMAIL PROTECTED] wrote:
> Use __repr__. Behold:
>
> >>> class NamedThing(object):
> def __init__(self, name):
> self.name = name
> def __repr__(self):
> return self.name
>
> >>> a = NamedThing("Delaware")
> >>> b = NamedThing("Hawaii")
> >>> d = {}
> >>> d[a] = 1
> >>> d[b] = 50
> >>> print d
> {Delaware: 1, Hawaii: 50}
> >>> d[a]
> 1
> >>> d[b]
> 50
>
> Although this is a bit illegal, because repr is not supposed to be used
> this way.
>
> Joel Hedlund wrote:
> > Hi!
> >
> > There's one thing about dictionaries and __hash__() methods that puzzle me.
> > I
> > have a class with several data members, one of which is 'name' (a str). I
> > would
> > like to store several of these objects in a dict for quick access
> > ({name:object} style). Now, I was thinking that given a list of objects I
> > might
> > do something like
> >
> > d = {}
> > for o in objects:
> > d[o] = o
> >
> > and still be able to retrieve the data like so:
> >
> > d[name]
> >
> > if I just defined a __hash__ method like so:
> >
> > def __hash__(self):
> > return self.name.__hash__()
> >
> > but this fails miserably. Feel free to laugh if you feel like it. I cooked
> > up a
> > little example with sample output below if you care to take the time.
> >
> > Code:
> > ---
> > class NamedThing(object):
> > def __init__(self, name):
> > self.name = name
> > def __hash__(self):
> > return self.name.__hash__()
> > def __repr__(self):
> > return ''
> > name = 'moo'
> > o = NamedThing(name)
> > print "This output puzzles me:"
> > d = {}
> > d[o] = o
> > d[name] = o
> > print d
> > print
> > print "If I wrap all keys in hash() calls I'm fine:"
> > d = {}
> > d[hash(o)] = o
> > d[hash(name)] = o
> > print d
> > print
> > print "But how come the first method didn't work?"
> > ---
> >
> > Output:
> > ---
> > This output puzzles me:
> > {'moo': , : }
> >
> > If I wrap all keys in hash() calls I'm fine:
> > {2038943316: }
> >
> > But how come the first method didn't work?
> > ---
> >
> > I'd be grateful if anyone can shed a litte light on this, or point me to
> > some
> > docs I might have missed.
> >
> > Also:
> > Am I in fact abusing the __hash__() method? If so - what's the intended use
> > of
> > the __hash__() method?
> >
> > Is there a better way of implementing this?
> >
> > I realise I could just write
> >
> > d[o.name] = o
> >
> > but this problem seems to pop up every now and then and I'm curious if
> > there's
> > some neat syntactic trick that I could legally apply here.
> >
> > Thanks for your time!
> > /Joel Hedlund
--
http://mail.python.org/mailman/listinfo/python-list
Re: constucting a lookup table
How about a dictionary, keyed on tuples of (height, weight)? [EMAIL PROTECTED] wrote: > I'm new to Python and want to contruct a "lookup table" which would be > similar to a spreadsheet in that a value is read along the first > column, then along the top row, and the intersection of the two gives a > value that is hard-coded, i.e. not mathmatically related. An example > would be a table with HEIGHT in the first column, WEIGHT in the first > row, and estimated SUITSIZE with the body of the table. > > Which Python type would be most appropriate and/or efficient? > > thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: regex help
Why not use split instead of regular expressions?
>>> ln = "3232 23 9 9 - 9 9 - 911
>>> 110"
>>> ln.split()
['32', '32', '23', '9', '9', '-', '9', '9', '-', '9', '11', '1', '10']
Much simpler, yes? Just find the line that comes after a line that
begins with "TIGER," split it, and pick the number you want out of the
resulting list.
Lance Hoffmeyer wrote:
> I have the following table and I am trying to match percentage the 2nd column
> on the 2nd Tiger line (9.0).
>
> I have tried both of the following. I expected both to match but neither
> did? Is there a modifier
> I am missing? What changes do I need to make these match? I need to keep
> the structure of the regex
> the same.
>
> TIGER.append(re.search("TIGER\s{10}.*?(?:(\d{1,3}\.\d)\s+){2}",
> target_table).group(1))
> TIGER.append(re.search("^TIGER.*?(?:(\d{1,3}\.\d)\s+){2}",
> target_table).group(1))
>
>
> BASE - TOTAL TIGER 268 268173 95 101 - 10157 -
> 5778 276 268 19276230 21
>
> DOG 7979 44 3531 -3117 -
> 1725 124795524 75 1
> 29.5 29.5 25.4 36.8 30.7 - 30.7 29.8 -
> 29.8 32.1 50.0 31.6 29.5 28.6 31.6 32.64.8
>
> CAT 4646 28 1820 -20 7 -
>714 -14463214 39 4
> 17.2 17.2 16.2 18.9 19.8 - 19.8 12.3 -
> 12.3 17.9 - 18.4 17.2 16.7 18.4 17.0 19.0
>
> LAMB3232 23 910 -10 8 -
>812 -12322012 28 1
> 11.9 11.9 13.39.5 9.9 - 9.9 14.0 -
> 14.0 15.4 - 15.8 11.9 10.4 15.8 12.24.8
>
> TRIPOD 3232 23 9 9 - 9 9 -
>911 110322210 28 3
> 11.9 11.9 13.39.5 8.9 - 8.9 15.8 -
> 15.8 14.1 50.0 13.2 11.9 11.5 13.2 12.2 14.3
>
> TIGER 2424 16 8 5 - 510 -
> 10 7 - 72417 7 18 2
>9.0 9.09.28.4 5.0 - 5.0 17.5 -
> 17.5 9.0 - 9.2 9.0 8.9 9.27.89.5
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help System For Python Applications
[EMAIL PROTECTED] wrote: > On a related note, is there a way to fire up Adobe's Acorbat Reader or > and Web Browser from Python and have the external application open a > specified PDF or HTML file? (For example, I want to open the file > "myhelp.pdf" in reader from Python code.) The webbrowser module lets you open any page. HTML will open in the user's default web browser; PDF opens in Acrobat (at least on my Windows machine). >>> import webbrowser >>> webbrowser.open(r"C:\\helpfile.pdf") -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: comapring two strings
manstey wrote:
> Hi,
>
> Is there a clever way to see if two strings of the same length vary by
> only one character, and what the character is in both strings.
You want zip.
def diffbyonlyone(string1, string2):
diffcount = 0
for c1, c2 in zip(string1, string2):
if c1 != c2:
diffcount += 1
if diffcount > 1:
return False
return diffcount == 1
print diffbyonlyone("yaqtil","yaqtel") # True
print diffbyonlyone("yiqtol","yaqtel") # False
If your strings are long, it might be faster/more memory efficient to
use itertools.izip instead.
> My next problem is, I have a list of 300,000+ words and I want to find
> every pair of such strings. I thought I would first sort on length of
> string, but how do I iterate through the following:
>
> str1
> str2
> str3
> str4
> str5
>
> so that I compare str1 & str2, str1 & str3, str 1 & str4, str1 & str5,
> str2 & str3, str3 & str4, str3 & str5, str4 & str5.
for index1 in xrange(len(words)):
for index2 in xrange(index1+1,len(words)):
if diffbyonlyone(words[index1], words[index2]):
print words[index1] + " -- " + words[index2]
...but by all means run that only on sets of words that you have
already identified, pursuant to some criteria like word length, to be
likely matches. Do the math; that's a lot of comparisons!
--
http://mail.python.org/mailman/listinfo/python-list
Re: time series calculation in list comprehension?
falcon wrote: > Is there a way I can do time series calculation, such as a moving > average in list comprehension syntax? I'm new to python but it looks > like list comprehension's 'head' can only work at a value at a time. I > also tried using the reduce function and passed in my list and another > function which calculates a moving average outside the list comp. ... > but I'm not clear how to do it. Any ideas? Thanks. I agree with others that reduce is not the best way to do this. But, to satisfy your curiosity, I offer this horribly inefficient way to use "reduce" to calculate the average of a list: from __future__ import division def reduceaverage(acc, x): return [acc[0] + x, acc[1] + 1, (acc[0] + x) / (acc[1] + 1) ] numbers = [4, 8, 15, 16, 23, 42] print reduce(reduceaverage, numbers, [0,0,0])[2] ...basically, the idea is to write a function that takes as its first argument the accumulated values, and as its second argument the next value in the list. In Python, this is almost always the wrong way to do something, but it is kind of geeky and LISP-ish. -- http://mail.python.org/mailman/listinfo/python-list
Re: trying to find repeated substrings with regular expression
Robert Dodier wrote: > I've decided it's easier for me just to search for FOO, and then > break up the string based on the locations of FOO. > > But I'd like to better understand regular expressions. Those who cannot learn regular expressions are doomed to repeat string searches. Which is not such a bad thing. txt = "blah FOO blah1a blah1b FOO blah2 FOO blah3a blah3b blah3b" def fa(s, pat): retlist = [] try: while True: i = s.rindex(pat) retlist.insert(0,s[i:]) s = s[:i] except: return retlist print fa(txt, "FOO") -- http://mail.python.org/mailman/listinfo/python-list
Re: recursive map on nested list
Uglier than yours, but down to two lines: def recur_map(f, data): return [ not hasattr(x, "__iter__") and f(x) or recur_map(f, x) for x in data ] -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions and matches
Johhny wrote:
> Hello,
>
> I have recently written a small function that will verify that an IP
> address is valid.
>
> ==SNIP==
>
> import re
> ipAddress = raw_input('IP Address : ')
>
> def validateIP(ipAddress):
> ipRegex =
> r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$"
Good lord! You might as well be writing in assembly! The re module
docs should include a customer warning label.
Regular expressions are not the answer here. Probably 80% of the regex
virus could be stamped out if people used split instead. How about
something simpler, like this:
def ipValid(ipAddress):
dots = ipAddress.split(".")
if len(dots) != 4:
return False
for item in dots:
if not 0 <= int(item) <= 255:
return False
return True
...although even this function (like yours) will declare as "valid" an
IP address like 0.255.0.0.
For a real-world application, how about:
import socket
try:
mm = socket.inet_aton(ipAddress)
return True # We got through that call without an error, so it is
valid
except socket.error:
return False # There was an error, so it is invalid
> re_ip = re.compile(ipRegex)
> match = re_ip.match(ipAddress)
> if not match:
> print "an error has occured with ipAddress"
> return match
> else:
> return match
>
> print(validateIP(ipAddress))
>
> ==SNIP==
>
> I was having issues trying to get my code working so that I could pass
> the IP addresses and it would return a true or false. When it matches I
> get something that looks like this.
>
> python ip_valid.py
> IP Address : 192.158.1.1
> <_sre.SRE_Match object at 0xb7de8c80>
>
> As I am still attempting to learn python I am interested to know how I
> could get the above to return a true or false if it matches or does not
> match the IP address. I would also like to expand that so that if the
> IP is wrong it requests the IP address again and recalls the function.
> I have done the same thing in php very easily but python appears to be
> getting the better of me. Any assistance and advice would be greatly
> appreciated.
>
> Regards,
>
> Johhny
--
http://mail.python.org/mailman/listinfo/python-list
