title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python PIL: color index to RGB
2,363,583
<p>following <a href="http://stackoverflow.com/questions/138250/read-the-rgb-value-of-a-given-pixel-in-python-programaticly">this link</a> i was able to load and read pixels from a .gif. That question specifically askes for a RGB value, but the accepted (and most voted answer) that I used as reference gets me to get an...
3
2010-03-02T14:02:16Z
2,363,867
<pre><code>img = Image.open(GIF_FILENAME) rgbimg = img.convert('RGB') for i in range(5): print rgbimg.getpixel((i, 0)) </code></pre>
5
2010-03-02T14:40:52Z
[ "python", "image" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,363,630
<p>It is good practice.</p> <blockquote> <p>My java-professor warns us never to use breaks in our loops</p> </blockquote> <p>Why is that? “never” is a strong word in computer science and should never (…) be used.<sup>1)</sup></p> <hr> <p><sup>1)</sup> Except for “goto” … we all have our pet peeves. ;-...
2
2010-03-02T14:09:29Z
[ "python", "for-loop", "while-loop" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,363,643
<p>There's nothing wrong with your example, but it's better to write</p> <pre><code>def func(self, foo): return any(foo.boolfunc() for foo in self.list) </code></pre>
14
2010-03-02T14:11:06Z
[ "python", "for-loop", "while-loop" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,363,683
<p>Your professor is advocating a practice called "Single point of Return", which basically states that any block of code should only have one point of exit. Breaks in loops are somewhat distinct from this, but usually lumped together.</p> <p>It's a controversial opinion, to say the least, and certainly not as hard an...
6
2010-03-02T14:16:59Z
[ "python", "for-loop", "while-loop" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,363,686
<p>"Breaking out of a loop" can easily devolve to bad practice because it conceals the terminating condition of the loop.</p> <p>If your <code>if</code> statement is of moderate complexity, then it can become unclear what post-condition the loop establishes.</p> <p>If your exit condition is <strong>obvious</strong>, ...
-2
2010-03-02T14:17:26Z
[ "python", "for-loop", "while-loop" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,363,807
<p>It should be mentioned that in Python, <a href="http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">for loops can have an else clause</a>. The else clause is only executed when the loop terminates through exhaustion of the list.</p> <p>So you could write:</p> <...
8
2010-03-02T14:34:14Z
[ "python", "for-loop", "while-loop" ]
returning out of for-loop
2,363,602
<p>I'm pretty new at python and I was wondering if this:</p> <pre><code>def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False </code></pre> <p>is good practice.</p> <p>Can I return out of a loop like the above or should i use a while-loop, like so?</p> <pre><code>def...
8
2010-03-02T14:05:40Z
2,364,598
<p>"Early exit" is a perfectly Pythonic style (when warranted: gnibbler's answer correctly points out that for your specific use case there's a built-in [[in Python 2.5 and better]] that's preferable) and often helps realize the Pythonic goal of "flat is better than nested". And <code>for</code> is usually the right w...
5
2010-03-02T16:08:52Z
[ "python", "for-loop", "while-loop" ]
Embedding Python code as a preprocessor PHP style
2,363,609
<p>I'm going back over an old project where I added preprocessor functionality to <a href="http://www.cs.york.ac.uk/aig/constraints/AutoModel/" rel="nofollow">Essence'</a> and I realised that my previous solution of writing a domain specific language and associated lexer/parser was overkill.</p> <p>Instead I just need...
2
2010-03-02T14:06:28Z
2,363,657
<p>Your best bet is to use one of the already made (and battle tested) Templating Engines. The two big ones that I've used are <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, and <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a>. They allow you to embed code right in the page, and ...
6
2010-03-02T14:12:34Z
[ "python" ]
append new row to old csv file python
2,363,731
<p>I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. </p> <p>Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.</p> <p>Wanted to know are there any better ways of doing this...
44
2010-03-02T14:23:33Z
2,363,742
<pre><code>fd = open('document.csv','a') fd.write(myCsvRow) fd.close() </code></pre> <p>Opening a file with the <code>'a'</code> parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.</p>
80
2010-03-02T14:25:51Z
[ "python", "csv", "append", "writer" ]
append new row to old csv file python
2,363,731
<p>I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. </p> <p>Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.</p> <p>Wanted to know are there any better ways of doing this...
44
2010-03-02T14:23:33Z
2,363,746
<p>Are you opening the file with mode of 'a' instead of 'w'?</p> <p>See <a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">Reading and Writing Files</a> in the python docs</p> <blockquote> <h1>7.2. Reading and Writing Files</h1> <p>open() returns a file object, ...
4
2010-03-02T14:26:11Z
[ "python", "csv", "append", "writer" ]
append new row to old csv file python
2,363,731
<p>I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. </p> <p>Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value.</p> <p>Wanted to know are there any better ways of doing this...
44
2010-03-02T14:23:33Z
37,654,233
<p>I prefer this solution using the <code>csv</code> module from the standard library and the <code>open</code> method to avoid leaving the file open.</p> <p>The key point is using <code>'a'</code> for appending when you open the file.</p> <pre><code>import csv fields=['first','second','third'] with open(r'name', ...
8
2016-06-06T09:46:15Z
[ "python", "csv", "append", "writer" ]
Comparing two lists items in python
2,363,954
<p>I have two files which I loaded into lists. The content of the first file is something like this:</p> <pre><code>d.complex.1 23 34 56 58 68 76 . . . etc d.complex.179 43 34 59 69 76 . . . etc </code></pre> <p>The content of the second file is also the same but with different numerical values. Please consider from ...
1
2010-03-02T14:51:20Z
2,364,138
<p>First create a function which can load a given file, as you may want to maintain individual sets and also want to count occurrence of each number, best would be to have a dict for whole file where keys are set names e.g. complex.1 etc, for each such set keep another dict for numbers in set, below code explains it be...
1
2010-03-02T15:14:55Z
[ "python", "file", "compare" ]
Comparing two lists items in python
2,363,954
<p>I have two files which I loaded into lists. The content of the first file is something like this:</p> <pre><code>d.complex.1 23 34 56 58 68 76 . . . etc d.complex.179 43 34 59 69 76 . . . etc </code></pre> <p>The content of the second file is also the same but with different numerical values. Please consider from ...
1
2010-03-02T14:51:20Z
2,364,191
<p>Open the file using Python's <code>open</code> function, then iterate over all its lines. Check whether the line contains a number, if so, increase its count in a <code>defaultdict</code> instance as described <a href="http://stackoverflow.com/questions/429414/whats-the-pythonic-way-to-count-the-occurrence-of-an-ele...
2
2010-03-02T15:19:14Z
[ "python", "file", "compare" ]
Find text in gtk.TextView
2,364,014
<p>I have a <code>gtk.Textview</code>. I want to find and select some of the text in this <code>TextView</code> programmatically. I have this code but it's not working correctly.</p> <pre><code>search_str = self.text_to_find.get_text() start_iter = textbuffer.get_start_iter() match_start = textbuffer.get_start_ite...
4
2010-03-02T14:58:16Z
2,368,364
<p><code>start_iter.forward_search</code> returns a tuple of the start and end matches so your <code>found</code> variable has both <code>match_start</code> and <code>match_end</code> in it</p> <p>this should make it work:</p> <pre><code>search_str = self.text_to_find.get_text() start_iter = textbuffer.get_start_it...
4
2010-03-03T02:27:25Z
[ "python", "gtk", "pygtk" ]
pyxmpp: quick tutorial for creating a muc client?
2,364,039
<p>I'm attempting to write a quick load-test script for our ejabberd cluster that simply logs into a chat room, posts a couple of random messages, then exits.</p> <p>We had attempted this particular test with tsung, but according to the authors, the muc functionality did not make it into this release.</p> <p>pyxmpp s...
6
2010-03-02T15:01:39Z
3,332,356
<p>Hey I stumbled over your question a few times, while trying the same thing. Here is my answer:</p> <p>Using <a href="http://pyxmpp.jajcus.net/svn/pyxmpp/trunk/examples/echobot.py" rel="nofollow">http://pyxmpp.jajcus.net/svn/pyxmpp/trunk/examples/echobot.py</a> as a quickstart, all you have to do is import the MUC-S...
6
2010-07-26T05:17:35Z
[ "python", "xmpp", "ejabberd", "multiuserchat" ]
Signing a string with RSA private key on Google App Engine Python SDK
2,364,084
<p>Is there any known way to sign a plain text string with RSA private key on Google App Engine Python SDK?</p>
7
2010-03-02T15:07:34Z
2,364,204
<p>I haven't used it, but this appears to be a pure-Python RSA implementation, so it might work on App Engine:</p> <p><a href="http://stuvel.eu/rsa" rel="nofollow">http://stuvel.eu/rsa</a></p> <p>Their <a href="http://hg.stuvel.eu/python-rsa" rel="nofollow">Mercurial repo</a> appears to be fairly active, too.</p>
3
2010-03-02T15:21:25Z
[ "python", "google-app-engine", "rsa" ]
Signing a string with RSA private key on Google App Engine Python SDK
2,364,084
<p>Is there any known way to sign a plain text string with RSA private key on Google App Engine Python SDK?</p>
7
2010-03-02T15:07:34Z
3,680,801
<p>The library tlslite included in the gdata python library is a good option.</p> <p><a href="http://code.google.com/p/gdata-python-client/">http://code.google.com/p/gdata-python-client/</a></p> <p>example:</p> <pre><code>from tlslite.utils import keyfactory private_key = keyfactory.parsePrivateKey(rsa_key) signed =...
6
2010-09-09T21:44:22Z
[ "python", "google-app-engine", "rsa" ]
Django + GAE (Google App Engine) : most convenient path for a beginner?
2,364,364
<p>Some background info first:</p> <ul> <li><strong>Goal:</strong> a medium-level complexity web app that I will need to maintain and possibly extend for a few years.</li> <li><strong>Experience:</strong> good knowledge of python, some experience of MVC frameworks (in PHP).</li> <li><strong>Desiderata:</strong> using ...
4
2010-03-02T15:40:48Z
2,366,349
<p>I'm not sure if Django is a good fit for you. Django is a great framework for standalone applications because it provides a full stack solution: an ORM, authentication system and an admin interface, to name a few. You won't be able to use any of these on App Engine. Furthermore, many of the code samples are geared t...
6
2010-03-02T20:03:43Z
[ "python", "django", "google-app-engine", "web-applications" ]
Avoiding nesting two for loops
2,364,382
<p>Please have a look at the code below:</p> <pre><code>import string from collections import defaultdict first_complex=open( "residue_a_chain_a_b_backup.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open(...
2
2010-03-02T15:42:40Z
2,364,411
<p>You want to convert <code>list_2</code> to a set, and check for membership:</p> <pre><code>list_1 = ['a', 'big', 'list'] list_2 = ['another', 'big', 'list'] target_set = set(list_2) for a in list_1: if a in target_set: print a </code></pre> <p>Outputs:</p> <pre><code>big list </code></pre> <p>A se...
8
2010-03-02T15:46:48Z
[ "python", "for-loop" ]
Avoiding nesting two for loops
2,364,382
<p>Please have a look at the code below:</p> <pre><code>import string from collections import defaultdict first_complex=open( "residue_a_chain_a_b_backup.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open(...
2
2010-03-02T15:42:40Z
2,364,655
<p>The following code perform the same tasks as yours with greater conciseness, directness, and speed:</p> <pre><code>with open('residue_a_chain_a_b_backup.txt', 'r') as f: list1 = [line for line in f if line[0] != 'd'] with open('residue_a_chain_a_c_backup.txt', 'r') as f: list2 = [line for line in f if line[0] !...
3
2010-03-02T16:15:19Z
[ "python", "for-loop" ]
Avoiding nesting two for loops
2,364,382
<p>Please have a look at the code below:</p> <pre><code>import string from collections import defaultdict first_complex=open( "residue_a_chain_a_b_backup.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open(...
2
2010-03-02T15:42:40Z
2,365,524
<p>Refining Alex's code very slightly:</p> <pre><code>with open('residue_a_chain_a_c_backup.txt', 'r') as f: set2 = set([line.strip() for line in f if line[0] != 'd']) with open('residue_a_chain_a_b_backup.txt', 'r') as f: list1 = [line.strip() for line in f if line.strip() in set2] </code></pre>
1
2010-03-02T18:07:20Z
[ "python", "for-loop" ]
Avoiding nesting two for loops
2,364,382
<p>Please have a look at the code below:</p> <pre><code>import string from collections import defaultdict first_complex=open( "residue_a_chain_a_b_backup.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open(...
2
2010-03-02T15:42:40Z
2,646,045
<p>Is it the intersection of two set you want, if so you can use the set interaction operation:</p> <pre><code>list_1 = ['a', 'big', 'list'] list_2 = ['another', 'big', 'list'] intersection = (set(list_1) &amp; set(list_2)) </code></pre> <p>After running this, <code>interaction</code> is a <code>set</code> containin...
2
2010-04-15T14:14:20Z
[ "python", "for-loop" ]
Google App Engine: Trouble with Datastore Query
2,364,531
<p>This query works:</p> <pre><code>item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0] </code></pre> <p>although if there are no results returned, it blows up in my face. (How can I get around this? A <code>for</code> loop seems dubious when I want at max one iteration.)</p> <p>This query does not work:</p>...
3
2010-03-02T16:01:48Z
2,364,698
<p>You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following:</p> <pre><code>&gt;&gt;&gt; results = [] # an empty list &gt;&gt;&gt; item = results[0] # Raises an IndexError, because there is nothing in the list </code></pre> <p>What you n...
9
2010-03-02T16:19:55Z
[ "python", "google-app-engine", "gae-datastore" ]
Google App Engine: Trouble with Datastore Query
2,364,531
<p>This query works:</p> <pre><code>item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0] </code></pre> <p>although if there are no results returned, it blows up in my face. (How can I get around this? A <code>for</code> loop seems dubious when I want at max one iteration.)</p> <p>This query does not work:</p>...
3
2010-03-02T16:01:48Z
2,364,708
<p>It seems that that your query returns an array or list of some sort, which is empty. Trying to access its non-existing first item raises an exception.</p> <p>Try to figure out the length of the returned result before accessing it.</p>
0
2010-03-02T16:21:20Z
[ "python", "google-app-engine", "gae-datastore" ]
Urlretrieve and User-Agent? - Python
2,364,593
<p>I'm using urlretrieve from the urllib module.</p> <p>I cannot seem to find how to add a User-Agent description to my requests.</p> <hr> <p>Is it possible with urlretrieve? or do I need to use another method?</p>
7
2010-03-02T16:08:16Z
2,364,647
<p>I don't think it's possible with urlretrieve - at least not easily. I would propose to create an urllib2.Request object and pass the required headers to it. See</p> <p><a href="http://docs.python.org/library/urllib2.html#urllib2.urlopen" rel="nofollow">http://docs.python.org/library/urllib2.html#urllib2.urlopen</a>...
2
2010-03-02T16:14:12Z
[ "python", "urllib" ]
Urlretrieve and User-Agent? - Python
2,364,593
<p>I'm using urlretrieve from the urllib module.</p> <p>I cannot seem to find how to add a User-Agent description to my requests.</p> <hr> <p>Is it possible with urlretrieve? or do I need to use another method?</p>
7
2010-03-02T16:08:16Z
7,059,232
<p>You can use URLopener or FancyURLopener classes. The 'version' argument specifies the user agent of the opener object.</p> <pre><code>opener = FancyURLopener({}) opener.version = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.69 Safari/537.36' opener.retrieve('http://e...
4
2011-08-14T19:41:03Z
[ "python", "urllib" ]
Urlretrieve and User-Agent? - Python
2,364,593
<p>I'm using urlretrieve from the urllib module.</p> <p>I cannot seem to find how to add a User-Agent description to my requests.</p> <hr> <p>Is it possible with urlretrieve? or do I need to use another method?</p>
7
2010-03-02T16:08:16Z
32,155,139
<p>First, set version:</p> <pre><code>urllib.URLopener.version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 SE 2.X MetaSr 1.0' </code></pre> <p>Then:</p> <pre><code>filename, headers = urllib.urlretrieve(url) </code></pre>
4
2015-08-22T10:37:48Z
[ "python", "urllib" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
2,364,716
<p><a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> is great. It is based on the Lex/Yacc idiom and thus may already be familiar. It allows you to create arbitrarily complex lexers and parsers for any task, including the one you need.</p> <p>Using a powerful tool like PLY instead of a simple toy is a good i...
2
2010-03-02T16:23:06Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
2,365,837
<p>While <code>ply</code> is a more classical approach (a Pythonic variant of lexx + yacc) and thus may be easier to get started with if you're already familiar with such traditional tools, <a href="http://pyparsing.wikispaces.com/">pyparsing</a> is highly pythonic and would be my top recommendation, especially for suc...
6
2010-03-02T18:57:44Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
2,371,091
<p><strong>SORRY - Lepl is no longer being developed.</strong></p> <p>There's also LEPL - <a href="http://www.acooke.org/lepl" rel="nofollow">http://www.acooke.org/lepl</a></p> <p>Here's a quick solution I wrote during breakfast:</p> <pre> pl6 src: python3 Python...
3
2010-03-03T12:19:12Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
18,331,789
<p>Whoosh has a comprehensive search query parser module whoosh.qparser and class QueryParser that should be reasonably easy to adapt to your use case.</p> <p>See <a href="http://pythonhosted.org/Whoosh/parsing.html" rel="nofollow">http://pythonhosted.org/Whoosh/parsing.html</a> and <a href="https://bitbucket.org/mcha...
0
2013-08-20T09:40:15Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
24,496,573
<p>A few good options:</p> <ul> <li><p>Whoosh: the only problem is that they have few parsing examples since the parser might not be its main feature/focus, but it's definitely a good option</p></li> <li><p>modgrammar: I didn't try it, but it seems pretty flexible and simple</p></li> <li><p>ply</p></li> <li><p>pyparsi...
2
2014-06-30T18:27:05Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
32,850,730
<p>I know this is an old question but for future reference I just uploaded my package <a href="http://searchstringparser.readthedocs.org/en/latest/" rel="nofollow">searchstringparser</a> to <a href="https://pypi.python.org/pypi/searchstringparser" rel="nofollow">PyPi</a>. Which implements a decent query parsing machine...
0
2015-09-29T17:56:07Z
[ "python", "string-parsing" ]
What is a good python parser for a google-like search query?
2,364,683
<p>For some search-based code (in Python), I need to write a query syntax parser that would parse a simple google like query syntax. For example:</p> <blockquote> <p>all of these words "with this phrase" OR that OR this site:within.site filetype:ps from:lastweek</p> </blockquote> <p>As search becomes more an mo...
14
2010-03-02T16:18:24Z
37,421,779
<p>PyParsing would be the right choice, although is quite tedious, thats why I have developed a query parser inspired on lucene and gmail syntax. It's only dependency is PyParsing, and we have used it on several projects. It is fully customizable and extendable, plus it abstracts you from the pyparsing issues. You can ...
1
2016-05-24T18:59:25Z
[ "python", "string-parsing" ]
Matplotlib runs out of memory when plotting in a loop
2,364,945
<p>I have a fairly simple plotting routine that looks like this:</p> <pre><code>from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(colu...
11
2010-03-02T16:50:50Z
2,365,027
<p>Although this is not a direct answer, I see that you intend to save the figure as a PNG using <code>savefig</code>. You can actually save a figure without displaying it first. That may avoid memory problems. For example, consider this code:</p> <pre><code>f = pylab.figure() ax = f.add_axes([0.1,0.1,0.8,0.8]) for i ...
1
2010-03-02T17:01:44Z
[ "python", "numpy", "matplotlib" ]
Matplotlib runs out of memory when plotting in a loop
2,364,945
<p>I have a fairly simple plotting routine that looks like this:</p> <pre><code>from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(colu...
11
2010-03-02T16:50:50Z
2,365,782
<p>Is each loop supposed to generate a new figure? I don't see you closing it or creating a new figure instance from loop to loop.</p> <p>This call will clear the current figure after you save it at the end of the loop:</p> <p>pyplot.clf()</p> <p>I'd refactor, though, and make your code more OO and create a new fig...
11
2010-03-02T18:48:41Z
[ "python", "numpy", "matplotlib" ]
Matplotlib runs out of memory when plotting in a loop
2,364,945
<p>I have a fairly simple plotting routine that looks like this:</p> <pre><code>from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(colu...
11
2010-03-02T16:50:50Z
7,889,179
<p>I've also run into this error. what seems to have fixed it is</p> <pre><code>while True: fig = pyplot.figure() ax = fig.add_subplot(111) ax.plot(x,y) ax.legend(legendStrings, loc = 'best') fig.savefig('himom.png') #new bit here pylab.close(fig) #where f is the figure </code></pre> <p>r...
17
2011-10-25T12:21:21Z
[ "python", "numpy", "matplotlib" ]
Matplotlib runs out of memory when plotting in a loop
2,364,945
<p>I have a fairly simple plotting routine that looks like this:</p> <pre><code>from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(colu...
11
2010-03-02T16:50:50Z
8,862,575
<p>Answer from ninjasmith worked for me too - <code>pyplot.close()</code> enabled my loops to work. </p> <p>From the pyplot tutorial, <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.close" rel="nofollow">Working with multiple figures and axes</a>:</p> <blockquote> <p>You can clear the current f...
6
2012-01-14T13:42:45Z
[ "python", "numpy", "matplotlib" ]
Python (Jython) Playing notes from pixels in picture
2,364,966
<p>This is from a class assignment:</p> <p><em>This program is about listening to colors. We will treat pictures as piano scores. Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pixel in every 4th row and do the following. ...
0
2010-03-02T16:53:42Z
2,365,684
<p>Robbie is right for the width/height for loops.</p> <p>The loop you are using to get the pixels and play the notes looks as if it is getting ALL the pixels and playing them all every time you get a unique x and y. What you should be doing is be getting the pixel at (x,y) then pulling out the rgb values and calling ...
1
2010-03-02T18:35:22Z
[ "python", "image-manipulation", "jython" ]
Python (Jython) Playing notes from pixels in picture
2,364,966
<p>This is from a class assignment:</p> <p><em>This program is about listening to colors. We will treat pictures as piano scores. Write a function called listenToPicture that takes one picture as an argument. It first shows the picture. Next, it will loop through every 4th pixel in every 4th row and do the following. ...
0
2010-03-02T16:53:42Z
2,365,825
<p>You asked about <a href="http://stackoverflow.com/questions/2337110/jython-image-manipulation-problem">similar things</a> before. Well, since you didn't put any code in about actually retrieving the pixel value, I'll assume that you still aren't able to do that. I know this is going way beyond your question, but las...
1
2010-03-02T18:55:32Z
[ "python", "image-manipulation", "jython" ]
Is there an IntelliJ Python plugin for the community edition?
2,365,126
<p>I've been playing with the community edition of JetBrains ItelliJ IDEA since it came out, and I really like it; however, a lot of plugins seem to require the ultimate edition (or at least I think they do because of the com.intellij.modules.ultimate dependency). Is there a python plugin that doesn't require the ultim...
8
2010-03-02T17:13:47Z
2,365,175
<p>Check out <a href="http://www.jetbrains.com/" rel="nofollow">PyCharm</a>.</p>
2
2010-03-02T17:19:58Z
[ "python", "django", "intellij-idea" ]
Is there an IntelliJ Python plugin for the community edition?
2,365,126
<p>I've been playing with the community edition of JetBrains ItelliJ IDEA since it came out, and I really like it; however, a lot of plugins seem to require the ultimate edition (or at least I think they do because of the com.intellij.modules.ultimate dependency). Is there a python plugin that doesn't require the ultim...
8
2010-03-02T17:13:47Z
19,608,269
<p>As of PyCharm 3.0, there is now a community edition of PyCharm. You can download it for free. It does not have all the features of the professional edition; however. Here is a comparison of the editions:</p> <p><a href="http://www.jetbrains.com/pycharm/features/editions_comparison_matrix.html" rel="nofollow">http:/...
0
2013-10-26T15:12:14Z
[ "python", "django", "intellij-idea" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
2,365,444
<pre><code>&gt;&gt;&gt; u'aあä'.encode('ascii', 'ignore') 'a' </code></pre> <p><strong>EDIT:</strong></p> <p>Decode the string you get back, using either the charset in the the appropriate <code>meta</code> tag in the response or in the <code>Content-Type</code> header, then encode.</p>
137
2010-03-02T17:56:45Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
2,365,581
<p>If you have a string <code>line</code>, you can use the <code>.encode([encoding], [errors='strict'])</code> method for strings to convert encoding types.</p> <p><code>line = 'my big string'</code></p> <p><code>line.encode('ascii', 'ignore')</code></p> <p>For more information about handling ASCII and unicode in Py...
4
2010-03-02T18:17:49Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
2,367,868
<p>I use this helper function throughout all of my projects. If it can't convert the unicode, it ignores it. This ties into a django library, but with a little research you could bypass it.</p> <pre><code>from django.utils import encoding def convert_unicode_to_string(x): """ &gt;&gt;&gt; convert_unicode_to_s...
21
2010-03-03T00:02:07Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
2,367,955
<p>You wrote """I assume that means the HTML contains some wrongly-formed attempt at unicode somewhere."""</p> <p>The HTML is NOT expected to contain any kind of "attempt at unicode", well-formed or not. It must of necessity contain Unicode characters encoded in some encoding, which is usually supplied up front ... lo...
5
2010-03-03T00:20:25Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
2,368,248
<p>Can we get the actual value used for <code>link</code>?</p> <p>In addition, we usually encounter this problem here when we are trying to <code>.encode()</code> an already encoded byte string. So you might try to decode it first as in</p> <pre><code>html = urllib.urlopen(link).read() unicode_str = html.decode(&lt;s...
72
2010-03-03T01:42:13Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
7,782,177
<p>As an extension to Ignacio Vazquez-Abrams' answer</p> <pre><code>&gt;&gt;&gt; u'aあä'.encode('ascii', 'ignore') 'a' </code></pre> <p>It is sometimes desirable to remove accents from characters and print the base form. This can be accomplished with</p> <pre><code>&gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unic...
78
2011-10-16T03:31:36Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
8,882,866
<p>For broken consoles like <code>cmd.exe</code> and HTML output you can always use:</p> <pre><code>my_unicode_string.encode('ascii','xmlcharrefreplace') </code></pre> <p>This will preserve all the non-ascii chars while making them printable in pure ASCII <em>and</em> in HTML.</p> <p><strong>WARNING</strong>: <em>If...
6
2012-01-16T16:16:36Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
25,681,172
<pre><code>unicodestring = '\xa0' decoded_str = unicodestring.decode("windows-1252") encoded_str = decoded_str.encode('ascii', 'ignore') </code></pre> <p>Works for me</p>
1
2014-09-05T08:00:29Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
29,552,191
<p>As a small note, for this to work in Python 3, you'll need to import unicodedata</p>
0
2015-04-10T02:09:32Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
35,536,228
<p>Use <strong><a href="https://pypi.python.org/pypi/Unidecode" rel="nofollow">unidecode</a></strong> - it even converts weird characters to ascii instantly, and even converts Chinese to phonetic ascii.</p> <pre><code>$ pip install unidecode </code></pre> <p>then:</p> <pre><code>&gt;&gt;&gt; from unidecode import un...
18
2016-02-21T12:38:51Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Python: Convert Unicode to ASCII without errors
2,365,411
<p>My code just scrapes a web page, then converts it to Unicode.</p> <pre><code>html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) </code></pre> <p>But I get a <code>UnicodeDecodeError</code>:</p> <hr> <pre><code>Traceback (most recent call last): File "/Applications/Goo...
103
2010-03-02T17:52:42Z
37,013,385
<p>Looks like you are using python 2.x. Python 2.x defaults to ascii and it doesn’t know about Unicode. Hence the exception.</p> <p>Just paste the below line after shebang, it will work</p> <pre><code># -*- coding: utf-8 -*- </code></pre>
-2
2016-05-03T20:04:28Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
Integrating SQLAlchemy's ORM with existing classes in pylons
2,365,459
<p>I have a class in my existing python project, User, that I would like to map to tables. But I'm not sure what the best way to do this is?</p> <p>Does this mean I can remove:</p> <pre><code>class User: pass </code></pre> <p>from my model/__ init __.py?</p> <p>Or should I leave that in there, and have somethi...
0
2010-03-02T17:58:40Z
4,090,305
<p>You should not define a class that maps onto a table in the model's __init__.py file, nor should you have two different clases with the same name. </p> <p>Classes that map onto tables belong in your project's model directory, grouped into modules. Then import the classes in __init__.py to make them available. </...
0
2010-11-03T18:25:20Z
[ "python", "orm", "sqlalchemy", "pylons" ]
Better looping, for string manipulation (python)
2,365,537
<p>If i have this code</p> <pre><code>s = 'abcdefghi' for grp in (s[:3],s[3:6],s[6:]): print "'%s'"%(grp) total = calc_total(grp) if (grp==s[:3]): # more code than this p = total + random_value x1 = my_function(p) if (grp==s[3:6]): # more code than this p = to...
0
2010-03-02T18:09:27Z
2,365,560
<p>I may have misunderstood what you're doing, but it appears that you want to do something to s[:3] on the first iteration, something different to s[3:6] on the second, and something else again to s[6:] on the third. In other words, that isn't a loop at all! Just write those three blocks of code out one after another,...
3
2010-03-02T18:13:35Z
[ "python", "loops", "for-loop" ]
Better looping, for string manipulation (python)
2,365,537
<p>If i have this code</p> <pre><code>s = 'abcdefghi' for grp in (s[:3],s[3:6],s[6:]): print "'%s'"%(grp) total = calc_total(grp) if (grp==s[:3]): # more code than this p = total + random_value x1 = my_function(p) if (grp==s[3:6]): # more code than this p = to...
0
2010-03-02T18:09:27Z
2,365,709
<pre><code>x = reduce(lambda x, grp: my_function(calc_total(list(grp)) + x), map(None, *[iter(s)] * 3), random_value) </code></pre> <p>At the end, you'll have the last <code>x</code>.</p> <p>Or, if you want to keep the intermediary results around,</p> <pre><code>x = [] for grp in map(None, *[iter(s)] * 3): ...
0
2010-03-02T18:40:02Z
[ "python", "loops", "for-loop" ]
Better looping, for string manipulation (python)
2,365,537
<p>If i have this code</p> <pre><code>s = 'abcdefghi' for grp in (s[:3],s[3:6],s[6:]): print "'%s'"%(grp) total = calc_total(grp) if (grp==s[:3]): # more code than this p = total + random_value x1 = my_function(p) if (grp==s[3:6]): # more code than this p = to...
0
2010-03-02T18:09:27Z
2,365,804
<p>I'd code something like this as follows:</p> <pre><code>for i, grp in enumerate((s[:3],s[3:6],s[6:])): print "'%s'"%(grp) total = calc_total(grp) # more code that needs to happen every time if i == 0: # code that needs to happen only the first time elif i == 1: # code that need...
0
2010-03-02T18:52:09Z
[ "python", "loops", "for-loop" ]
Better looping, for string manipulation (python)
2,365,537
<p>If i have this code</p> <pre><code>s = 'abcdefghi' for grp in (s[:3],s[3:6],s[6:]): print "'%s'"%(grp) total = calc_total(grp) if (grp==s[:3]): # more code than this p = total + random_value x1 = my_function(p) if (grp==s[3:6]): # more code than this p = to...
0
2010-03-02T18:09:27Z
2,366,047
<p>Get your data into the list you want, then try the following:</p> <pre><code>output = 0 seed = get_random_number() for group in input_list: total = get_total(group) p = total + seed seed = my_function(p) </code></pre> <p><code>input_list</code> will need to look like <code>['abc', 'def', 'ghi']</code>....
0
2010-03-02T19:24:30Z
[ "python", "loops", "for-loop" ]
Better looping, for string manipulation (python)
2,365,537
<p>If i have this code</p> <pre><code>s = 'abcdefghi' for grp in (s[:3],s[3:6],s[6:]): print "'%s'"%(grp) total = calc_total(grp) if (grp==s[:3]): # more code than this p = total + random_value x1 = my_function(p) if (grp==s[3:6]): # more code than this p = to...
0
2010-03-02T18:09:27Z
10,105,322
<p>I must say I agree with Peter in that the loop is redundant. If you are afraid of duplicating code, then just move the repeating code into a function and call it multiple times:</p> <pre><code>s = 'abcdefghi' def foo(grp): # Anything more you would like to happen over and over again print "'%s'"%(grp) ...
1
2012-04-11T11:50:40Z
[ "python", "loops", "for-loop" ]
Designing to easily migrate to Google App Engine
2,365,647
<p>I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future.</p> <p>Alternatively, I could design the app for GAE from the start, and so in...
6
2010-03-02T18:29:21Z
2,365,730
<p>Just out of top of my head:</p> <ul> <li>It's really ONLY a key->value store, don't be fooled by things like <a href="http://code.google.com/intl/pl-PL/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">GQL</a> (which is just a subset of SQL SELECT)</li> <li>No JOINs - often you have to denormalize o...
7
2010-03-02T18:42:43Z
[ "python", "google-app-engine", "relational-database", "web2py", "non-relational-database" ]
Decorating python class methods, how do I pass the instance to the decorator?
2,365,701
<p>This is python 2.5, it's <a href="https://developers.google.com/appengine/docs/python/">GAE</a> too not that it matters. </p> <p>I have the following code, I'm decorating the foo() method in bar, using the dec_check class as a decorator.</p> <pre><code>class dec_check(object): def __init__(self, f): self.fu...
44
2010-03-02T18:38:03Z
2,365,754
<p>Decorators can be a little tricky in Python. Here's an example of one I got to work sometime back. You might be able to infer from it what you're trying to do.</p> <p><a href="http://stackoverflow.com/questions/312925/django-authentication-and-ajax-urls-that-require-login/523196#523196">http://stackoverflow.com/q...
1
2010-03-02T18:45:37Z
[ "python" ]
Decorating python class methods, how do I pass the instance to the decorator?
2,365,701
<p>This is python 2.5, it's <a href="https://developers.google.com/appengine/docs/python/">GAE</a> too not that it matters. </p> <p>I have the following code, I'm decorating the foo() method in bar, using the dec_check class as a decorator.</p> <pre><code>class dec_check(object): def __init__(self, f): self.fu...
44
2010-03-02T18:38:03Z
2,365,771
<p>You need to make the decorator into a <a href="http://users.rcn.com/python/download/Descriptor.htm">descriptor</a> -- either by ensuring its (meta)class has a <code>__get__</code> method, or, <strong>way</strong> simpler, by using a decorator <em>function</em> instead of a decorator <em>class</em> (since functions a...
62
2010-03-02T18:47:35Z
[ "python" ]
Decorating python class methods, how do I pass the instance to the decorator?
2,365,701
<p>This is python 2.5, it's <a href="https://developers.google.com/appengine/docs/python/">GAE</a> too not that it matters. </p> <p>I have the following code, I'm decorating the foo() method in bar, using the dec_check class as a decorator.</p> <pre><code>class dec_check(object): def __init__(self, f): self.fu...
44
2010-03-02T18:38:03Z
3,296,318
<p>Alex's answer suffices when a function is sufficient. However When you need a class you can make it work by adding the following method to the decorator class.</p> <pre><code>def __get__(self, obj, objtype): """Support instance methods.""" import functools return functools.partial(self.__call__, obj) </...
36
2010-07-21T04:28:13Z
[ "python" ]
Jinja2 in Google App Engine
2,365,774
<p>I have started using <a href="http://jinja.pocoo.org/2/documentation/">Jinja2</a> as my templating engine on Google App Engine (in Python).</p> <p>My question is this: Will bytecode caching work in production? It is working very well on the development server, but I read somewhere that bytecode caching depends on t...
12
2010-03-02T18:47:40Z
2,369,184
<p>Rodrigo Moraes created some special loaders for Jinja2 under GAE, see <a href="http://groups.google.com/group/google-appengine-python/browse_thread/thread/04d4bf3dd615ed1e/2907cdeff922710c">here</a>. It's not bytecode caching but it precompiles all templates to Python so you avoid the Jinja2 parsing overhead.</p> <...
12
2010-03-03T06:25:49Z
[ "python", "google-app-engine", "caching", "jinja2" ]
Jinja2 in Google App Engine
2,365,774
<p>I have started using <a href="http://jinja.pocoo.org/2/documentation/">Jinja2</a> as my templating engine on Google App Engine (in Python).</p> <p>My question is this: Will bytecode caching work in production? It is working very well on the development server, but I read somewhere that bytecode caching depends on t...
12
2010-03-02T18:47:40Z
9,003,292
<p>Jinja2 is now included in GAE. Apparently you need to migrate your app to Python 2.7.</p> <p>In app.yaml add</p> <pre><code>libraries: - name: jinja2 version: "2.6" </code></pre> <p>Here is the source of this information: <a href="http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-template...
9
2012-01-25T13:11:27Z
[ "python", "google-app-engine", "caching", "jinja2" ]
Jinja2 in Google App Engine
2,365,774
<p>I have started using <a href="http://jinja.pocoo.org/2/documentation/">Jinja2</a> as my templating engine on Google App Engine (in Python).</p> <p>My question is this: Will bytecode caching work in production? It is working very well on the development server, but I read somewhere that bytecode caching depends on t...
12
2010-03-02T18:47:40Z
11,132,289
<p>According to the <a href="https://developers.google.com/appengine/docs/python/python27/newin27#Bytecode_Upload" rel="nofollow">What's New in Python 2.7 docs</a>, with Python 2.7 you can also upload .pyc files.</p> <blockquote> <p>Can upload .pyc files, but not in combination with .py files. However, you can uploa...
1
2012-06-21T05:54:03Z
[ "python", "google-app-engine", "caching", "jinja2" ]
haskell vs python typing
2,365,783
<p>I am looking for example where things in python would be easier to program just because it is dynamically typed? </p> <p>I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance...
2
2010-03-02T18:48:54Z
2,365,869
<blockquote> <p>Can I program in Haskell as I can in python without static typing being a hindrance</p> </blockquote> <p>Yes. </p> <p>To elaborate, I would say the main gotcha will be the use of existential types in Haskell for heterogeneous data structures (regular data structures holding lists of variously typed ...
7
2010-03-02T19:01:37Z
[ "python", "dynamic", "haskell", "static", "types" ]
haskell vs python typing
2,365,783
<p>I am looking for example where things in python would be easier to program just because it is dynamically typed? </p> <p>I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance...
2
2010-03-02T18:48:54Z
2,365,873
<p>Well for one you can't create a list containing multiple types of values without wrappers (like to get a list that may contain a string or an int, you'd have to create a list of <code>Either Int String</code> and wrap each item in a <code>Left</code> or a <code>Right</code>).</p> <p>You also can't define a function...
5
2010-03-02T19:02:14Z
[ "python", "dynamic", "haskell", "static", "types" ]
haskell vs python typing
2,365,783
<p>I am looking for example where things in python would be easier to program just because it is dynamically typed? </p> <p>I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance...
2
2010-03-02T18:48:54Z
2,366,124
<p>Like Chris said, this is one objective question (what can a dynamically typed language do that a statically typed one can't?) and one subjective question (can I use Haskell without static typing being a hindrance). So you're going to get mostly subjective answers, because the first question is not as interesting.</p...
4
2010-03-02T19:36:43Z
[ "python", "dynamic", "haskell", "static", "types" ]
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
2,365,876
<p>In Python 2.6, I can run the following fine to strip out chars like <code>-()</code></p> <pre><code>'(123) 456-7890'.translate(None, '-(), ') </code></pre> <p>Python2.5 translate does not accept None, how can I do the above in 2.5?</p>
1
2010-03-02T19:03:18Z
2,365,969
<p>That should be possible with <code>maketrans</code>:</p> <pre><code>import string '(123) 456-7890'.translate(string.maketrans('', ''), '-(), ') </code></pre> <p>But you can also use regular expressions which is more readable.</p>
3
2010-03-02T19:15:35Z
[ "python" ]
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
2,365,876
<p>In Python 2.6, I can run the following fine to strip out chars like <code>-()</code></p> <pre><code>'(123) 456-7890'.translate(None, '-(), ') </code></pre> <p>Python2.5 translate does not accept None, how can I do the above in 2.5?</p>
1
2010-03-02T19:03:18Z
2,365,970
<p>Regular Expressions.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub('\-|\(|\)| ','','(123) 456-7890') 1234567890 </code></pre>
0
2010-03-02T19:15:36Z
[ "python" ]
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
2,365,876
<p>In Python 2.6, I can run the following fine to strip out chars like <code>-()</code></p> <pre><code>'(123) 456-7890'.translate(None, '-(), ') </code></pre> <p>Python2.5 translate does not accept None, how can I do the above in 2.5?</p>
1
2010-03-02T19:03:18Z
2,366,058
<p>Use <a href="http://docs.python.org/library/string.html#string.maketrans" rel="nofollow"><code>string.maketrans</code></a> with empty arguments to create the <em>identity translation table</em>:</p> <blockquote> <p><code>string.maketrans(from, to)</code></p> <p>Return a translation table suitable for passing...
3
2010-03-02T19:27:10Z
[ "python" ]
What's the Python2.5 equivalent of Python2.6 translate with None as first param?
2,365,876
<p>In Python 2.6, I can run the following fine to strip out chars like <code>-()</code></p> <pre><code>'(123) 456-7890'.translate(None, '-(), ') </code></pre> <p>Python2.5 translate does not accept None, how can I do the above in 2.5?</p>
1
2010-03-02T19:03:18Z
2,527,771
<p>As an alternative, you can always keep only the digits:</p> <pre><code>def strip_nondigits(text): return filter(type(text).isdigit, text) &gt;&gt;&gt; strip_nondigits('(123) 456-7890') '1234567890' </code></pre> <p>This should be more robust against spurious characters. The <code>type(text)</code> makes it wo...
1
2010-03-27T01:20:24Z
[ "python" ]
Python interface for outputting MIDI files or text that's readable by audio programs
2,365,884
<p>I am looking for a python package or library that will allow me to programmatically output a file format (e.g. MIDI) that can be read by audio/sound processing programs, like LogicPro or iDrum. What are the best options for this?</p>
1
2010-03-02T19:04:06Z
2,366,126
<p>A large number of possibilities are listed <a href="http://wiki.python.org/moin/PythonInMusic" rel="nofollow">here</a>, especially under the "Midi Mania" header. For your requirements, and the various packages' descriptions, it seems to me that <a href="http://www.mxm.dk/products/public/pythonmidi" rel="nofollow">py...
1
2010-03-02T19:36:49Z
[ "python", "audio", "midi" ]
merging Python dictionaries
2,365,921
<p>I am trying to merge the following python dictionaries as follow:</p> <pre><code>dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} </code></pre> <p>Is ...
19
2010-03-02T19:08:53Z
2,365,976
<pre><code>output = dict((k, [dict1[k], dict2.get(k)]) for k in dict1) output.update((k, [None, dict2[k]]) for k in dict2 if k not in dict1) </code></pre>
19
2010-03-02T19:16:33Z
[ "python", "list", "dictionary", "merge" ]
merging Python dictionaries
2,365,921
<p>I am trying to merge the following python dictionaries as follow:</p> <pre><code>dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} </code></pre> <p>Is ...
19
2010-03-02T19:08:53Z
2,365,991
<p>This will work:</p> <pre><code>dict((k, [dict1.get(k), dict2.get(k)]) for k in set(dict1.keys() + dict2.keys())) </code></pre> <p>Output:</p> <pre><code>{'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]} </code></pre>
13
2010-03-02T19:18:11Z
[ "python", "list", "dictionary", "merge" ]
merging Python dictionaries
2,365,921
<p>I am trying to merge the following python dictionaries as follow:</p> <pre><code>dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} </code></pre> <p>Is ...
19
2010-03-02T19:08:53Z
2,366,205
<p><b>In Python3.1,</b><br> <pre><code>output = {k:[dict1.get(k),dict2.get(k)] for k in dict1.keys() | dict2.keys()}<br/></pre></code> <b>In Python2.6,</b><br/> <pre><code>output = dict((k,[dict1.get(k),dict2.get(k)]) for k in set(dict1.keys() + dict2.keys()))</pre></code></p>
1
2010-03-02T19:44:51Z
[ "python", "list", "dictionary", "merge" ]
merging Python dictionaries
2,365,921
<p>I am trying to merge the following python dictionaries as follow:</p> <pre><code>dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} </code></pre> <p>Is ...
19
2010-03-02T19:08:53Z
2,366,681
<p>In <strong>Python2.7</strong> or <strong>Python3.1</strong> you can easily generalise to work with any number of dictionaries using a combination of list, set and dict comprehensions!</p> <pre><code>&gt;&gt;&gt; dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10} &gt;&gt;&gt; dict2 = {'paul':'a', 'john':'b', 'ted...
7
2010-03-02T20:56:24Z
[ "python", "list", "dictionary", "merge" ]
Using Python, how do I read and extract data from a binary data file with multiple variable-length records?
2,365,998
<p>Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records.</p> <p>I've got...
2
2010-03-02T19:18:36Z
2,366,078
<p>18 MB should fit comfortably in memory, so I'd just gulp the whole thing into one big string of bytes with a single <code>with open(thefile, 'rb') as f: data = f.read()</code> and then perform all the "parsing" on slices to advance record by record. It's more convenient, and may well be faster than doing many small...
2
2010-03-02T19:31:09Z
[ "python", "gps", "binary-data" ]
Using Python, how do I read and extract data from a binary data file with multiple variable-length records?
2,365,998
<p>Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records.</p> <p>I've got...
2
2010-03-02T19:18:36Z
2,366,092
<p>You have to read in pieces. Not because of memory constraints, but because of the parsing requirements. 18MiB fits in memory easily. On a 4Gb machine it fits in memory 200 times over.</p> <p>Here's the usual design pattern.</p> <ol> <li><p>Read the first 4 bytes only. Use <code>struct</code> to unpack just tho...
5
2010-03-02T19:32:56Z
[ "python", "gps", "binary-data" ]
Using Python, how do I read and extract data from a binary data file with multiple variable-length records?
2,365,998
<p>Using Python (3.1 or 2.6), I'm trying to read data from binary data files produced by a GPS receiver. Data for each hour is stored in a separate file, each of which is about 18 MiB. The data files have multiple variable-length records, but for now I need to extract data from just one of the records.</p> <p>I've got...
2
2010-03-02T19:18:36Z
2,366,141
<p>Apart from writing a parser that correctly reads the file, you <em>may</em> try a somewhat brute-force approach...read the data to the memory and split it using the 'Sync' sentinel. Warning - you might get some false positives. But...</p> <pre><code>f = open('filename') data = f.read() messages = data.split('\xaa\x...
1
2010-03-02T19:38:00Z
[ "python", "gps", "binary-data" ]
Python Boto S3 to work with Custom Domains in Amazon S3
2,366,093
<p>How do I use the Python Boto library with S3 where the URL's it generate will be my CNAME'd subdomain to the Amazon S3 Server. </p> <p>By default it uses the default format <strong>BUCKETNAME.s3.amazonaws.com</strong> but S3 supports custom domain aliasing using CNAME (so you can have custom.domain.com -> CNAME -> ...
4
2010-03-02T19:33:02Z
3,965,603
<ol> <li>Your CNAME records must be already pointing to your S3 bucket.</li> <li>Your S3 bucket needs to also be named custom.domain.com</li> <li>Verify you are able to access your files from custom.domain.com in your browser.</li> </ol> <p>Once that's done, the following snippet I wrote will print the URL's to all th...
2
2010-10-19T05:35:30Z
[ "python", "subdomain", "cname", "boto", "amazon-s3" ]
Python: split a full name "First Last", "First Middle Last," etc ... into separate variables?
2,366,197
<p>I'm looking for the best way to write a function that takes a string in the form:</p> <p>"First" "First Last" "First Middle Last" "First M. Last" "First Second Third Last"</p> <p>And can return a python a list with each of the values separated.</p> <p>Thanks.</p>
1
2010-03-02T19:43:58Z
2,366,216
<p>Use the <a href="http://docs.python.org/library/stdtypes.html#str.split"><code>split</code></a> function:</p> <pre><code>&gt;&gt;&gt; s = "First Middle Last" &gt;&gt;&gt; s.split(" ") ['First', 'Middle', 'Last'] </code></pre>
7
2010-03-02T19:46:17Z
[ "python" ]
Python: split a full name "First Last", "First Middle Last," etc ... into separate variables?
2,366,197
<p>I'm looking for the best way to write a function that takes a string in the form:</p> <p>"First" "First Last" "First Middle Last" "First M. Last" "First Second Third Last"</p> <p>And can return a python a list with each of the values separated.</p> <p>Thanks.</p>
1
2010-03-02T19:43:58Z
35,085,266
<p>Andrew Hare is correct, however if you want to split on whitespace, loose the <code>" "</code> parameter.<br> The default is whitespace and is more robust:</p> <pre><code>&gt;&gt;&gt; ' a b c '.strip().split(" ") ['a', 'b', '', '', '', '', 'c'] &gt;&gt;&gt; ' a b c '.strip().split() ['a', 'b', 'c']...
0
2016-01-29T13:03:36Z
[ "python" ]
Can you go to a line with the file operations in python?
2,366,448
<p>I'm parsing a file and need to keep track of where I am in the file... let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file with the tell() method of the file. Is there a way to mark the...
3
2010-03-02T20:20:03Z
2,366,471
<p>Keep track of what <code>f.tell()</code> reports (usually the number of bytes, but not necessarily), then you can jump directly to the right position in the file.</p> <p>If you only keep track of the number of lines, you will have to read the file again from the beginning, counting the number of new lines seen.</p>...
1
2010-03-02T20:23:58Z
[ "python" ]
Can you go to a line with the file operations in python?
2,366,448
<p>I'm parsing a file and need to keep track of where I am in the file... let's say I have file test.txt and I'm doing a while loop that reads in data constantly as each line is written to the file. In case of a crash I'm marking my position in another file with the tell() method of the file. Is there a way to mark the...
3
2010-03-02T20:20:03Z
2,366,642
<p>You may like this better: <a href="http://docs.python.org/library/linecache.html" rel="nofollow">http://docs.python.org/library/linecache.html</a></p> <p>"In case of a crash I'm marking my position in another file with the tell() method of the file."</p> <p>Good.</p> <p>"Is there a way to mark the line and be abl...
2
2010-03-02T20:51:25Z
[ "python" ]
CAC Client Application Authentication in Python
2,366,636
<p>I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests.</p> <p>Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like <a hre...
4
2010-03-02T20:50:46Z
2,367,725
<p>You are correct. That's the whole purpose of the smart card to keep the private keys safe. If your application is running in Windows you can try using WININET.DLL for your connectivity, with the correct middleware installed it should handle authentication to the CAC enabled site automatically.</p>
0
2010-03-02T23:30:03Z
[ "python", "smartcard", "pkcs#11", "cac" ]
CAC Client Application Authentication in Python
2,366,636
<p>I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests.</p> <p>Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like <a hre...
4
2010-03-02T20:50:46Z
2,369,168
<p>Authentication and signature keys are usually generated on the card and are not extractable, unlike encryption keys which can/should be escrowed somewhere.</p> <p>See <a href="http://stackoverflow.com/questions/2195179/need-help-using-m2crypto-engine-to-access-usb-token">http://stackoverflow.com/questions/2195179/n...
4
2010-03-03T06:21:00Z
[ "python", "smartcard", "pkcs#11", "cac" ]
CAC Client Application Authentication in Python
2,366,636
<p>I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests.</p> <p>Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like <a hre...
4
2010-03-02T20:50:46Z
2,724,393
<p>I would attempt to find out if an ECA cert is a suitable substitute. For example, there sites that accept CAC and ECA certs. For more info: <a href="http://iase.disa.mil/pki/eca/certificate.html" rel="nofollow">http://iase.disa.mil/pki/eca/certificate.html</a></p>
0
2010-04-27T19:31:53Z
[ "python", "smartcard", "pkcs#11", "cac" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
2,366,777
<p>You will have access to the class of the object on which the method is being called in the decorated method that your decorator should return. Like so:</p> <pre><code>def decorator(method): # do something that requires view's class def decorated(self, *args, **kwargs): print 'My class is %s' % self...
0
2010-03-02T21:07:34Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
2,367,120
<p>The problem is that when the decorator is called the class doesn't exist yet. Try this:</p> <pre><code>def loud_decorator(func): print("Now decorating %s" % func) def decorated(*args, **kwargs): print("Now calling %s with %s,%s" % (func, args, kwargs)) return func(*args, **kwargs) return...
3
2010-03-02T21:55:31Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
2,367,288
<p>As Ants indicated, you can't get a reference to the class from within the class. However, if you're interested in distinguishing between different classes ( not manipulating the actual class type object), you can pass a string for each class. You can also pass whatever other parameters you like to the decorator usi...
2
2010-03-02T22:20:17Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
2,367,605
<p>If you are using Python 2.6 or later you could use a class decorator, perhaps something like this (warning: untested code).</p> <pre><code>def class_decorator(cls): for name, method in cls.__dict__.iteritems(): if hasattr(method, "use_class"): # do something with the method and class ...
41
2010-03-02T23:10:56Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
6,683,238
<p>As others have pointed out, the class hasn't been created at the time the decorator is called. <strong>However</strong>, it's possible to annotate the function object with the decorator parameters, then re-decorate the function in the metaclass's <code>__new__</code> method. You'll need to access the function's <cod...
11
2011-07-13T17:46:46Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
15,777,042
<p>What <a href="http://pythonhosted.org/Flask-Classy/" rel="nofollow">flask-classy</a> does is create a temporary cache that it stores on the method, then it uses something else (the fact that Flask will register the classes using a <code>register</code> class method) to actually wraps the method.</p> <p>You can reus...
1
2013-04-03T00:49:53Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
18,456,071
<p>Here's a simple example: </p> <pre><code>def mod_bar(cls): # returns modified class def decorate(fcn): # returns decorated function def new_fcn(self): print self.start_str print fcn(self) print self.end_str return new_fcn cls.bar = decorate...
3
2013-08-27T02:39:15Z
[ "python", "decorator" ]
Can a Python decorator of an instance method access the class?
2,366,713
<p>Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.</p> <pre><code>def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object...
61
2010-03-02T20:59:47Z
31,996,329
<p>This is an old question but came across venusian. <a href="http://venusian.readthedocs.org/en/latest/" rel="nofollow">http://venusian.readthedocs.org/en/latest/</a></p> <p>It seems to have the ability to decorate methods and give you access to both the class and the method while doing so. Note tht calling <code>se...
1
2015-08-13T18:57:32Z
[ "python", "decorator" ]
Is there a way to specify a fixed (or variable) number of elements for lxml in Python
2,367,000
<p>There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list ...
1
2010-03-02T21:40:13Z
2,367,031
<p>Use something like <a href="http://simplehtmldom.sourceforge.net/" rel="nofollow">simplehtmldom</a>, and then provide an index?</p>
0
2010-03-02T21:43:47Z
[ "python", "html", "lxml", "screen-scraping" ]
Is there a way to specify a fixed (or variable) number of elements for lxml in Python
2,367,000
<p>There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list ...
1
2010-03-02T21:40:13Z
2,367,066
<p>Does this do the trick?</p> <pre><code>from itertools import islice ancestor = islice(theitem.iterancestors(), 4) # To get the fourth ancestor </code></pre> <p><strong>EDIT</strong> I'm an idiot, that doesn't do the trick. You'll need to wrap it up in a helper function like so:</p> <pre><code>def nthparent(eleme...
1
2010-03-02T21:48:58Z
[ "python", "html", "lxml", "screen-scraping" ]
Is there a way to specify a fixed (or variable) number of elements for lxml in Python
2,367,000
<p>There must be an easier way to do this. I need some text from a large number of html documents. In my tests the most reliable way to find it is to look for specific word in the text_content of the div elements. If I want to inspect a specific element above the one that has my text I have been enumerating my list ...
1
2010-03-02T21:40:13Z
2,367,102
<p><a href="http://codespeak.net/lxml/xpathxslt.html#xpath" rel="nofollow">lxml</a> supports <a href="http://www.w3.org/TR/xpath/" rel="nofollow">XPath</a>:</p> <pre><code>from lxml import etree root = etree.fromstring("...your xml...") el, = root.xpath("//div[text() = 'the string']/preceding-sibling::*[9]") </code><...
3
2010-03-02T21:53:23Z
[ "python", "html", "lxml", "screen-scraping" ]