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
sequence |
---|---|---|---|---|---|---|---|---|---|
Which is faster in Python: x**.5 or math.sqrt(x)? | 327,002 | <p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p>
<p><b>UPDATE</b></p>
<p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p>
<p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p>
<h3>My email:</h3>
<blockquote>
<p>There are at least 3 ways to do a square root in Python: math.sqrt, the
'**' operator and pow(x,.5). I'm just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?</p>
</blockquote>
<h3>His response:</h3>
<blockquote>
<p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea...</p>
</blockquote>
| 116 | 2008-11-29T01:24:09Z | 327,063 | <p>using Claudiu's code, on my machine even with "from math import sqrt" x**.5 is faster but using psyco.full() sqrt(x) becomes much faster, at least by 200%</p>
| 4 | 2008-11-29T02:28:52Z | [
"python",
"performance"
] |
Which is faster in Python: x**.5 or math.sqrt(x)? | 327,002 | <p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p>
<p><b>UPDATE</b></p>
<p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p>
<p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p>
<h3>My email:</h3>
<blockquote>
<p>There are at least 3 ways to do a square root in Python: math.sqrt, the
'**' operator and pow(x,.5). I'm just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?</p>
</blockquote>
<h3>His response:</h3>
<blockquote>
<p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea...</p>
</blockquote>
| 116 | 2008-11-29T01:24:09Z | 2,695,986 | <p>Claudiu's results differ from mine. I'm using Python 2.6 on Ubuntu on an old P4 2.4Ghz machine... Here's my results:</p>
<pre><code>>>> timeit1()
Took 0.564911 seconds
>>> timeit2()
Took 0.403087 seconds
>>> timeit1()
Took 0.604713 seconds
>>> timeit2()
Took 0.387749 seconds
>>> timeit1()
Took 0.587829 seconds
>>> timeit2()
Took 0.379381 seconds
</code></pre>
<p>sqrt is consistently faster for me... Even Codepad.org NOW seems to agree that sqrt, in the local context, is faster (<a href="http://codepad.org/6trzcM3j" rel="nofollow">http://codepad.org/6trzcM3j</a>). Codepad seems to be running Python 2.5 presently. Perhaps they were using 2.4 or older when Claudiu first answered?</p>
<p>In fact, even using math.sqrt(i) in place of arg(i), I still get better times for sqrt. In this case timeit2() took between 0.53 and 0.55 seconds on my machine, which is still better than the 0.56-0.60 figures from timeit1.</p>
<p>I'd say, on modern Python, use math.sqrt and definitely bring it to local context, either with somevar=math.sqrt or with from math import sqrt.</p>
| 0 | 2010-04-23T03:14:26Z | [
"python",
"performance"
] |
Which is faster in Python: x**.5 or math.sqrt(x)? | 327,002 | <p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p>
<p><b>UPDATE</b></p>
<p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p>
<p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p>
<h3>My email:</h3>
<blockquote>
<p>There are at least 3 ways to do a square root in Python: math.sqrt, the
'**' operator and pow(x,.5). I'm just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?</p>
</blockquote>
<h3>His response:</h3>
<blockquote>
<p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea...</p>
</blockquote>
| 116 | 2008-11-29T01:24:09Z | 2,696,173 | <p>In python 2.6 the <code>(float).__pow__()</code> function uses the C <code>pow()</code> function and the <code>math.sqrt()</code> functions uses the C <code>sqrt()</code> function.</p>
<p>In glibc compiler the implementation of <code>pow(x,y)</code> is quite complex and it is well optimized for various exceptional cases. For example, calling C <code>pow(x,0.5)</code> simply calls the <code>sqrt()</code> function.</p>
<p>The difference in speed of using <code>.**</code> or <code>math.sqrt</code> is caused by the wrappers used around the C functions and the speed strongly depends on optimization flags/C compiler used on the system. </p>
<p><strong>Edit:</strong></p>
<p>Here are the results of Claudiu's algorithm on my machine. I got different results:</p>
<pre><code>zoltan@host:~$ python2.4 p.py
Took 0.173994 seconds
Took 0.158991 seconds
zoltan@host:~$ python2.5 p.py
Took 0.182321 seconds
Took 0.155394 seconds
zoltan@host:~$ python2.6 p.py
Took 0.166766 seconds
Took 0.097018 seconds
</code></pre>
| 4 | 2010-04-23T04:17:49Z | [
"python",
"performance"
] |
Which is faster in Python: x**.5 or math.sqrt(x)? | 327,002 | <p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p>
<p><b>UPDATE</b></p>
<p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p>
<p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p>
<h3>My email:</h3>
<blockquote>
<p>There are at least 3 ways to do a square root in Python: math.sqrt, the
'**' operator and pow(x,.5). I'm just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?</p>
</blockquote>
<h3>His response:</h3>
<blockquote>
<p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea...</p>
</blockquote>
| 116 | 2008-11-29T01:24:09Z | 2,696,402 | <p>Someone commented about the "fast Newton-Raphson square root" from Quake 3... I implemented it with ctypes, but it's super slow in comparison to the native versions. I'm going to try a few optimizations and alternate implementations.</p>
<pre><code>from ctypes import c_float, c_long, byref, POINTER, cast
def sqrt(num):
xhalf = 0.5*num
x = c_float(num)
i = cast(byref(x), POINTER(c_long)).contents.value
i = c_long(0x5f375a86 - (i>>1))
x = cast(byref(i), POINTER(c_float)).contents.value
x = x*(1.5-xhalf*x*x)
x = x*(1.5-xhalf*x*x)
return x * num
</code></pre>
<p>Here's another method using struct, comes out about 3.6x faster than the ctypes version, but still 1/10 the speed of C.</p>
<pre><code>from struct import pack, unpack
def sqrt_struct(num):
xhalf = 0.5*num
i = unpack('L', pack('f', 28.0))[0]
i = 0x5f375a86 - (i>>1)
x = unpack('f', pack('L', i))[0]
x = x*(1.5-xhalf*x*x)
x = x*(1.5-xhalf*x*x)
return x * num
</code></pre>
| 2 | 2010-04-23T05:27:31Z | [
"python",
"performance"
] |
Which is faster in Python: x**.5 or math.sqrt(x)? | 327,002 | <p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p>
<p><b>UPDATE</b></p>
<p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p>
<p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p>
<h3>My email:</h3>
<blockquote>
<p>There are at least 3 ways to do a square root in Python: math.sqrt, the
'**' operator and pow(x,.5). I'm just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?</p>
</blockquote>
<h3>His response:</h3>
<blockquote>
<p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea...</p>
</blockquote>
| 116 | 2008-11-29T01:24:09Z | 29,231,648 | <p>What would be even faster is if you went into math.py and copied the function "sqrt" into your program. It takes time for your program to find math.py, then open it, find the function you are looking for, and then bring that back to your program. If that function is faster even with the "lookup" steps, then the function itself has to be awfully fast. Probably will cut your time in half. IN summary:</p>
<ol>
<li>Go to math.py</li>
<li>Find the function "sqrt"</li>
<li>Copy it</li>
<li>Paste function into your program as the sqrt finder.</li>
<li>Time it.</li>
</ol>
| -2 | 2015-03-24T11:37:06Z | [
"python",
"performance"
] |
Attribute BOLD doesn't seem to work in my curses | 327,026 | <p>I use something like this:
screen.addstr(text, color_pair(1) | A_BOLD), but it doesn't seem to work..
However, A_REVERSE and all others attribute does work! </p>
<p>In fact, I'm trying to print something in white, but the COLOR_WHITE prints it gray.. and after a while of searching, it seems that printing it gray + BOLD makes it! </p>
<p>Any helps would be greatly appreciated.</p>
| 3 | 2008-11-29T01:46:53Z | 327,072 | <p>Here's an example code (Python 2.6, Linux):</p>
<pre><code>#!/usr/bin/env python
from itertools import cycle
import curses, contextlib, time
@contextlib.contextmanager
def curses_screen():
"""Contextmanager's version of curses.wrapper()."""
try:
stdscr=curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
try: curses.start_color()
except: pass
yield stdscr
finally:
stdscr.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
if __name__=="__main__":
with curses_screen() as stdscr:
c = curses.A_BOLD
if curses.has_colors():
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
c |= curses.color_pair(1)
curses.curs_set(0) # make cursor invisible
y, x = stdscr.getmaxyx()
for col in cycle((c, curses.A_BOLD)):
stdscr.erase()
stdscr.addstr(y//2, x//2, 'abc', col)
stdscr.refresh()
time.sleep(1)
</code></pre>
<p>All seems to be working.</p>
| 4 | 2008-11-29T02:38:50Z | [
"python",
"linux",
"curses",
"bold"
] |
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other | 327,142 | <p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p>
<p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
| 3 | 2008-11-29T04:01:45Z | 327,237 | <p>Well, if they have the same project and application names, then the databases and tables will be the same. Your django_session table which holds the session information is the same for both sites. You have to use different project names that will go in different MySQL (or whatever) databases.</p>
| 0 | 2008-11-29T05:56:53Z | [
"python",
"django",
"admin"
] |
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other | 327,142 | <p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p>
<p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
| 3 | 2008-11-29T04:01:45Z | 327,296 | <p>The session information is stored in the database, so if you're sharing the database with both running instances, logging off one location will log you off both. If your circumstance requires you to share the database, the easiest workaround is probably to create a second user account with admin privileges.</p>
| 0 | 2008-11-29T07:06:58Z | [
"python",
"django",
"admin"
] |
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other | 327,142 | <p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p>
<p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
| 3 | 2008-11-29T04:01:45Z | 327,307 | <p>Set the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain">SESSION_COOKIE_DOMAIN</a> option. You need to set the domain for each of your sites so the cookies don't override each other.</p>
<p>You can also use SESSION_COOKIE_NAME to make the cookie names different for each site.</p>
| 7 | 2008-11-29T07:27:35Z | [
"python",
"django",
"admin"
] |
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other | 327,142 | <p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p>
<p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
| 3 | 2008-11-29T04:01:45Z | 327,398 | <p>Let me guess, is this running on your localhost? and you have each site assigned to a different port? i.e. localhost:8000, localhost:8001 ..?</p>
<p>I've had the same problem! (although I wasn't running Apache per se)</p>
<p>When you login to the admin site, you get a cookie in your browser that's associated with the domain "localhost", the cookie stores a pointer of some sort to a session stored in the database on the server. </p>
<p>When you visit the other site, the server tries to interpret the cookie, but fails. I'm guessing it deletes the cookie because it's "garbage".</p>
<p>What you can do in this case, is change your domain</p>
<p>use localhost:8000 for the first site, and 127.0.0.1:8001 for the second site. this way the second site doesn't attempt to read the cookie that was set by the first site</p>
<p>I also think you can edit your HOSTS file to add more aliases to 127.0.0.1 if you need to. (but I haven't tried this)</p>
| 0 | 2008-11-29T10:08:50Z | [
"python",
"django",
"admin"
] |
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other | 327,142 | <p>I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. </p>
<p>Everything about the actual public facing applications works fine. When I log into either of the admin sites it seems ok, but if I switch and do any work on the opposite admin site I get logged out of the first one. In short I can't be logged into both admin sites at once. Any help would be appreciated.</p>
| 3 | 2008-11-29T04:01:45Z | 1,007,356 | <p>I ran into a similar issue with a live & staging site hosted on the same Apache server (on CentOS). I added unique SESSION_COOKIE_NAME values to each site's settings (in local_settings.py, create one if you don't have one and import it in your settings.py), set the SESSION_COOKIE_DOMAIN for the live site and set SESSION_COOKIE_DOMAIN = None for staging. I also ran "python manage.py cleanup" to (hopefully) clean any conflicted information out of the database.</p>
| 0 | 2009-06-17T14:23:25Z | [
"python",
"django",
"admin"
] |
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order? | 327,191 | <p>The list sort method is a modifier function that returns None.</p>
<p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p>
<pre>
for k in somedictionary.keys().sort():
dosomething()
</pre>
<p>instead, i must:</p>
<pre>
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
</pre>
<p>Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?</p>
| 2 | 2008-11-29T05:03:14Z | 327,195 | <p>Can I answer my own question?</p>
<p>I have just discovered the handy function "sorted" which does exactly what I was looking for.</p>
<pre>
for k in sorted(somedictionary.keys()):
dosomething()
</pre>
<p>It shows up in <a href="http://stackoverflow.com/questions/157424/python-25-dictionary-2-key-sort">http://stackoverflow.com/questions/157424/python-25-dictionary-2-key-sort</a></p>
| 6 | 2008-11-29T05:06:35Z | [
"python",
"iterator",
"syntactic-sugar"
] |
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order? | 327,191 | <p>The list sort method is a modifier function that returns None.</p>
<p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p>
<pre>
for k in somedictionary.keys().sort():
dosomething()
</pre>
<p>instead, i must:</p>
<pre>
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
</pre>
<p>Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?</p>
| 2 | 2008-11-29T05:03:14Z | 327,210 | <pre><code>for k in sorted(somedictionary.keys()):
doSomething(k)
</code></pre>
<p>Note that you can also get all of the keys and values sorted by keys like this:</p>
<pre><code>for k, v in sorted(somedictionary.iteritems()):
doSomething(k, v)
</code></pre>
| 17 | 2008-11-29T05:20:37Z | [
"python",
"iterator",
"syntactic-sugar"
] |
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order? | 327,191 | <p>The list sort method is a modifier function that returns None.</p>
<p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p>
<pre>
for k in somedictionary.keys().sort():
dosomething()
</pre>
<p>instead, i must:</p>
<pre>
keys = somedictionary.keys()
keys.sort()
for k in keys:
dosomething()
</pre>
<p>Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?</p>
| 2 | 2008-11-29T05:03:14Z | 856,272 | <p>Actually, .keys() is not necessary:</p>
<pre><code>for k in sorted(somedictionary):
doSomething(k)
</code></pre>
<p>or </p>
<pre><code>[doSomethinc(k) for k in sorted(somedict)]
</code></pre>
| 6 | 2009-05-13T05:54:38Z | [
"python",
"iterator",
"syntactic-sugar"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,254 | <p>You could try to use same dictionary, only one level deep.</p>
<pre><code>topDictionary[word1+delimiter+word2+delimiter+word3]
</code></pre>
<p>delimiter could be plain " ". (or use (word1,word2,word3))</p>
<p>This would be easiest to implement.
I believe you will see a little improvement, if it is not enough...
...i'll think of something...</p>
| 1 | 2008-11-29T06:21:59Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,285 | <p>A couple attempts:</p>
<p>I figure you're doing something similar to this:</p>
<pre><code>from __future__ import with_statement
import time
from collections import deque, defaultdict
# Just used to generate some triples of words
def triplegen(words="/usr/share/dict/words"):
d=deque()
with open(words) as f:
for i in range(3):
d.append(f.readline().strip())
while d[-1] != '':
yield tuple(d)
d.popleft()
d.append(f.readline().strip())
if __name__ == '__main__':
class D(dict):
def __missing__(self, key):
self[key] = D()
return self[key]
h=D()
for a, b, c in triplegen():
h[a][b][c] = 1
time.sleep(60)
</code></pre>
<p>That gives me ~88MB.</p>
<p>Changing the storage to</p>
<pre><code>h[a, b, c] = 1
</code></pre>
<p>takes ~25MB</p>
<p>interning a, b, and c makes it take about 31MB. My case is a bit special because my words never repeat on the input. You might try some variations yourself and see if one of these helps you.</p>
| 3 | 2008-11-29T06:59:32Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,295 | <p>Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record:</p>
<pre><code>295760 S. Lott's answer
237984 S. Lott's with keys interned before passing in
203172 [*] d[(a,b,c)] = int(freq)
203156 d[a][b][c] = int(freq)
189132 keys.append((a,b,c)); freqs.append(int(freq))
146132 d[intern(a),intern(b)][intern(c)] = int(freq)
145408 d[intern(a)][intern(b)][intern(c)] = int(freq)
83888 [*] d[a+' '+b+' '+c] = int(freq)
82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq)
68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq))
60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq))
50556 pair array
48320 squeezed pair array
33024 squeezed single array
</code></pre>
<p>The entries marked [*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.)</p>
<p>'Pair array' is the scheme below in my original answer ("I'd start with the array with keys
being the first two words..."), where the value table for each pair is
represented as a single string. 'Squeezed pair array' is the same,
leaving out the frequency values that are equal to 1 (the most common
case). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code:</p>
<pre><code>import collections
def build(file):
pairs = collections.defaultdict(list)
for line in file: # N.B. file assumed to be already sorted
a, b, c, freq = line.split()
key = ' '.join((a, b))
pairs[key].append(c + ':' + freq if freq != '1' else c)
out = open('squeezedsinglearrayfile', 'w')
for key in sorted(pairs.keys()):
out.write('%s|%s\n' % (key, ' '.join(pairs[key])))
def load():
return open('squeezedsinglearrayfile').readlines()
if __name__ == '__main__':
build(open('freqs'))
</code></pre>
<p>I haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below.</p>
<p><strong>Original answer:</strong> A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using <a href="http://www.python.org/doc/2.5.2/lib/module-zlib.html">zlib</a>? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options.</p>
<p>Also, binary tree structures are <em>not</em> recommended for memory efficiency here. E.g., <a href="http://www.cdf.toronto.edu/~csc148h/fall/assignment3/bursttries.pdf">this paper</a> tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure.</p>
<p>I should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.)</p>
| 26 | 2008-11-29T07:06:58Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,299 | <p>You could put all words in a dictionary.
key would be word, and value is number (index).</p>
<p>Then you use it like this:</p>
<pre><code>Word1=indexDict[word1]
Word2=indexDict[word2]
Word3=indexDict[word3]
topDictionary[Word1][Word2][Word3]
</code></pre>
<p>Insert in indexDict with:</p>
<pre><code>if word not in indexDict:
indexDict[word]=len(indexDict)
</code></pre>
| -1 | 2008-11-29T07:11:47Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,313 | <p>Use tuples.<br />
Tuples can be keys to dictionaries, so you don't need to nest dictionaries.</p>
<pre><code>d = {}
d[ word1, word2, word3 ] = 1
</code></pre>
<p>Also as a plus, you could use defaultdict </p>
<ul>
<li>so that elements that don't have entries always return 0</li>
<li>and so that u can say <code>d[w1,w2,w3] += 1</code> without checking if the key already exists or not</li>
</ul>
<p>example:</p>
<pre><code>from collections import defaultdict
d = defaultdict(int)
d["first","word","tuple"] += 1
</code></pre>
<p>If you need to find all words "word3" that are tupled with (word1,word2) then search for it in dictionary.keys() using list comprehension</p>
<p>if you have a tuple, t, you can get the first two items using slices:</p>
<pre><code>>>> a = (1,2,3)
>>> a[:2]
(1, 2)
</code></pre>
<p>a small example for searching tuples with list comprehensions:</p>
<pre><code>>>> b = [(1,2,3),(1,2,5),(3,4,6)]
>>> search = (1,2)
>>> [a[2] for a in b if a[:2] == search]
[3, 5]
</code></pre>
<p>You see here, we got a list of all items that appear as the third item in the tuples that start with (1,2)</p>
| 8 | 2008-11-29T07:36:31Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,459 | <p>Ok, so you are basically trying to store a sparse 3D space. The kind of access patterns you want to this space is crucial for the choice of algorithm and data structure. Considering your data source, do you want to feed this to a grid? If you don't need O(1) access:</p>
<p>In order to get memory efficiency you want to subdivide that space into subspaces with a similar number of entries. (like a BTree). So a data structure with :</p>
<ul>
<li>firstWordRange</li>
<li>secondWordRange</li>
<li>thirdWordRange</li>
<li>numberOfEntries</li>
<li>a sorted block of entries.</li>
<li>next and previous blocks in all 3 dimensions</li>
</ul>
| 1 | 2008-11-29T11:44:40Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,464 | <p>In this case, <a href="http://www.zope.org/Products/StandaloneZODB" rel="nofollow">ZODB</a>¹ BTrees might be helpful, since they are much less memory-hungry. Use a BTrees.OOBtree (Object keys to Object values) or BTrees.OIBTree (Object keys to Integer values), and use 3-word tuples as your key.</p>
<p>Something like:</p>
<pre><code>from BTrees.OOBTree import OOBTree as BTree
</code></pre>
<p>The interface is, more or less, dict-like, with the added bonus (for you) that <code>.keys</code>, <code>.items</code>, <code>.iterkeys</code> and <code>.iteritems</code> have two <code>min, max</code> optional arguments:</p>
<pre><code>>>> t=BTree()
>>> t['a', 'b', 'c']= 10
>>> t['a', 'b', 'z']= 11
>>> t['a', 'a', 'z']= 12
>>> t['a', 'd', 'z']= 13
>>> print list(t.keys(('a', 'b'), ('a', 'c')))
[('a', 'b', 'c'), ('a', 'b', 'z')]
</code></pre>
<p>¹ Note that if you are on Windows and work with Python >2.4, I know there are packages for more recent python versions, but I can't recollect where.</p>
<p>PS They exist in the <a href="http://pypi.python.org/pypi/ZODB3" rel="nofollow">CheeseShop</a> âº</p>
| 4 | 2008-11-29T11:50:18Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,479 | <p>Are you implementing Markovian text generation?</p>
<p>If your chains map 2 words to the probabilities of the third I'd use a dictionary mapping K-tuples to the 3rd-word histogram. A trivial (but memory-hungry) way to implement the histogram would be to use a list with repeats, and then <code>random.choice</code> gives you a word with the proper probability.</p>
<p>Here's an implementation with the K-tuple as a parameter:</p>
<pre><code>import random
# can change these functions to use a dict-based histogram
# instead of a list with repeats
def default_histogram(): return []
def add_to_histogram(item, hist): hist.append(item)
def choose_from_histogram(hist): return random.choice(hist)
K=2 # look 2 words back
words = ...
d = {}
# build histograms
for i in xrange(len(words)-K-1):
key = words[i:i+K]
word = words[i+K]
d.setdefault(key, default_histogram())
add_to_histogram(word, d[key])
# generate text
start = random.randrange(len(words)-K-1)
key = words[start:start+K]
for i in NUM_WORDS_TO_GENERATE:
word = choose_from_histogram(d[key])
print word,
key = key[1:] + (word,)
</code></pre>
| 2 | 2008-11-29T12:14:17Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,481 | <p>If memory is simply not big enough, <a href="http://www.jcea.es/programacion/pybsddb.htm" rel="nofollow">pybsddb</a> can help store a disk-persistent map.</p>
| 0 | 2008-11-29T12:18:27Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,697 | <p>You could use a numpy multidimensional array. You'll need to use numbers rather than strings to index into the array, but that can be solved by using a single dict to map words to numbers.</p>
<pre><code>import numpy
w = {'word1':1, 'word2':2, 'word3':3, 'word4':4}
a = numpy.zeros( (4,4,4) )
</code></pre>
<p>Then to index into your array, you'd do something like:</p>
<pre><code>a[w[word1], w[word2], w[word3]] += 1
</code></pre>
<p>That syntax is not beautiful, but numpy arrays are about as efficient as anything you're likely to find. Note also that I haven't tried this code out, so I may be off in some of the details. Just going from memory here.</p>
| 0 | 2008-11-29T16:52:46Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 327,924 | <p>Here's a tree structure that uses the bisect library to maintain a sorted list of words. Each lookup in <strong>O</strong>(log2(n)).</p>
<pre><code>import bisect
class WordList( object ):
"""Leaf-level is list of words and counts."""
def __init__( self ):
self.words= [ ('\xff-None-',0) ]
def count( self, wordTuple ):
assert len(wordTuple)==1
word= wordTuple[0]
loc= bisect.bisect_left( self.words, word )
if self.words[loc][0] != word:
self.words.insert( loc, (word,0) )
self.words[loc]= ( word, self.words[loc][1]+1 )
def getWords( self ):
return self.words[:-1]
class WordTree( object ):
"""Above non-leaf nodes are words and either trees or lists."""
def __init__( self ):
self.words= [ ('\xff-None-',None) ]
def count( self, wordTuple ):
head, tail = wordTuple[0], wordTuple[1:]
loc= bisect.bisect_left( self.words, head )
if self.words[loc][0] != head:
if len(tail) == 1:
newList= WordList()
else:
newList= WordTree()
self.words.insert( loc, (head,newList) )
self.words[loc][1].count( tail )
def getWords( self ):
return self.words[:-1]
t = WordTree()
for a in ( ('the','quick','brown'), ('the','quick','fox') ):
t.count(a)
for w1,wt1 in t.getWords():
print w1
for w2,wt2 in wt1.getWords():
print " ", w2
for w3 in wt2.getWords():
print " ", w3
</code></pre>
<p>For simplicity, this uses a dummy value in each tree and list. This saves endless if-statements to determine if the list was actually empty before we make a comparison. It's only empty once, so the if-statements are wasted for all <em>n</em>-1 other words.</p>
| 1 | 2008-11-29T19:48:04Z | [
"python",
"memory",
"data-structures"
] |
Memory Efficient Alternatives to Python Dictionaries | 327,223 | <p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc.</p>
<p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p>
<p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p>
<p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p>
<p>So, does anyone have any suggestions for me?</p>
<p>Edited to add:</p>
<p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). </p>
<p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
<p>Once again, thank you all for the responses so far.</p>
| 32 | 2008-11-29T05:33:26Z | 331,384 | <p>Scipy has sparse matrices, so if you can make the first two words a tuple, you can do something like this:</p>
<pre><code>import numpy as N
from scipy import sparse
word_index = {}
count = sparse.lil_matrix((word_count*word_count, word_count), dtype=N.int)
for word1, word2, word3 in triple_list:
w1 = word_index.setdefault(word1, len(word_index))
w2 = word_index.setdefault(word2, len(word_index))
w3 = word_index.setdefault(word3, len(word_index))
w1_w2 = w1 * word_count + w2
count[w1_w2,w3] += 1
</code></pre>
| 1 | 2008-12-01T16:42:46Z | [
"python",
"memory",
"data-structures"
] |
Why is the Python readline module not available on OS X? | 327,251 | <p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p>
<pre>
$ uname -a
Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386
$ which python
/usr/bin/python
$ python
Python 2.3.5 (#1, Nov 26 2007, 09:16:55)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named readline
>>>
</pre>
<p>I have also installed Python 2.5 through MacPorts but <code>readline</code> is not available there either.</p>
<p>What can I do to provide <code>readline</code> functionality for Python's <code>raw_input()</code> function on OS X?</p>
| 4 | 2008-11-29T06:18:49Z | 327,262 | <p>It's not shipped in OS X because of licensing issues (restrictions brought to you by the GPL).</p>
<p>Macports python should be fine if you have the readline package installed.</p>
| 3 | 2008-11-29T06:29:39Z | [
"python",
"osx",
"readline"
] |
Why is the Python readline module not available on OS X? | 327,251 | <p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p>
<pre>
$ uname -a
Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386
$ which python
/usr/bin/python
$ python
Python 2.3.5 (#1, Nov 26 2007, 09:16:55)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named readline
>>>
</pre>
<p>I have also installed Python 2.5 through MacPorts but <code>readline</code> is not available there either.</p>
<p>What can I do to provide <code>readline</code> functionality for Python's <code>raw_input()</code> function on OS X?</p>
| 4 | 2008-11-29T06:18:49Z | 327,292 | <p>Have you tried to install the <code>py-readline</code> (or <code>py25-readline</code> for Python 2.5) port?</p>
<p>Also, in the snippet above, you are NOT using the MacPort python, but rather the Apple Python.</p>
<p>The MacPort version should be located in the <code>/opt/local</code> directory structure. You should check your path.</p>
| 6 | 2008-11-29T07:05:00Z | [
"python",
"osx",
"readline"
] |
Why is the Python readline module not available on OS X? | 327,251 | <p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p>
<pre>
$ uname -a
Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386
$ which python
/usr/bin/python
$ python
Python 2.3.5 (#1, Nov 26 2007, 09:16:55)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named readline
>>>
</pre>
<p>I have also installed Python 2.5 through MacPorts but <code>readline</code> is not available there either.</p>
<p>What can I do to provide <code>readline</code> functionality for Python's <code>raw_input()</code> function on OS X?</p>
| 4 | 2008-11-29T06:18:49Z | 1,114,882 | <p>You should be able to get readline support on Mac's native Python. Apparently it's implemented via BSD's editline, and you have to start it up slightly differently. I just tested this on a Mac, and it works fine (OS X 10.5.7). See <code>man python</code> for more details, the section "Interactive Input Editing and History Substitution" - <a href="http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/python.1.html" rel="nofollow">mirrored on the web here</a>.</p>
<pre><code>luga ~ $ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import rlcompleter
>>> import readline
>>>
</code></pre>
| 3 | 2009-07-11T23:05:09Z | [
"python",
"osx",
"readline"
] |
Why is the Python readline module not available on OS X? | 327,251 | <p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="nofollow"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p>
<pre>
$ uname -a
Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386
$ which python
/usr/bin/python
$ python
Python 2.3.5 (#1, Nov 26 2007, 09:16:55)
[GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named readline
>>>
</pre>
<p>I have also installed Python 2.5 through MacPorts but <code>readline</code> is not available there either.</p>
<p>What can I do to provide <code>readline</code> functionality for Python's <code>raw_input()</code> function on OS X?</p>
| 4 | 2008-11-29T06:18:49Z | 38,943,793 | <p>Try <code>rlwrap</code>. It should work with any version of python and in general any shell.</p>
<p>Install via <code>brew install rlwrap</code> on Mac OS X</p>
<p>usage as <code>rlwrap python</code>. It stores history as well.</p>
| 0 | 2016-08-14T15:38:39Z | [
"python",
"osx",
"readline"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 327,317 | <p>It is a hash table. You can read about it some in the <a href="http://wiki.python.org/moin/DictionaryKeys" rel="nofollow">python wiki</a>. Otherwise, the code is well-written and should be easy to understand.</p>
| 4 | 2008-11-29T07:40:18Z | [
"python",
"data-structures",
"dictionary"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 327,378 | <p><a href="http://pybites.blogspot.com/2008/10/pure-python-dictionary-implementation.html">Pure Python Dictionary Implementation</a></p>
<blockquote>
<p>For those curious about how CPython's dict implementation works, I've written a Python implementation using the same algorithms.</p>
</blockquote>
| 8 | 2008-11-29T09:22:46Z | [
"python",
"data-structures",
"dictionary"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 334,953 | <p>Here's a link to the <a href="http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=66801&view=auto" title="dict implementation">actual implementation</a> in the python SVN repository. That should be the most definite answer.</p>
| 8 | 2008-12-02T18:29:16Z | [
"python",
"data-structures",
"dictionary"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 2,996,689 | <p>Python Dictionaries use <a href="http://en.wikipedia.org/wiki/Hash_table#Open_addressing">Open addressing</a> (<a href="http://books.google.co.in/books?id=gJrmszNHQV4C&lpg=PP1&hl=sv&pg=PA298#v=onepage&q&f=false">reference inside Beautiful code</a>)</p>
<p><strong>NB!</strong> <em>Open addressing</em>, a.k.a <em>closed hashing</em> should, as noted in Wikipedia, not be confused with its opposite <em>open hashing</em>! (which we see in the accepted answer).</p>
<p>Open addressing means that the dict uses array slots, and when an object's primary position is taken in the dict, the object's spot is sought at a different index in the same array, using a "perturbation" scheme, where the object's hash value plays part.</p>
| 37 | 2010-06-08T11:00:37Z | [
"python",
"data-structures",
"dictionary"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 8,682,049 | <p>At PyCon 2010, Brandon Craig Rhodes gave an <a href="http://www.youtube.com/watch?v=C4Kc8xzcA68">excellent talk</a> about the Python dictionary. It provides a great overview of the dictionary implementation with examples and visuals. If you have 45 minutes (or even just 15), I would recommend watching the talk before proceeding to the actual implementation.</p>
| 27 | 2011-12-30T17:15:04Z | [
"python",
"data-structures",
"dictionary"
] |
How are Python's Built In Dictionaries Implemented | 327,311 | <p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
| 146 | 2008-11-29T07:35:31Z | 9,022,835 | <p>Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). </p>
<ul>
<li>Python dictionaries are implemented as <strong>hash tables</strong>.</li>
<li>Hash tables must allow for <strong>hash collisions</strong> i.e. even if two distinct keys have the same hash value, the table's implementation must have a strategy to insert and retrieve the key and value pairs unambiguously.</li>
<li>Python <code>dict</code> uses <strong>open addressing</strong> to resolve hash collisions (explained below) (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l296">dictobject.c:296-297</a>).</li>
<li>Python hash table is just a contiguous block of memory (sort of like an array, so you can do an <code>O(1)</code> lookup by index). </li>
<li><strong>Each slot in the table can store one and only one entry.</strong> This is important.</li>
<li>Each <strong>entry</strong> in the table actually a combination of the three values: <strong>< hash, key, value ></strong>. This is implemented as a C struct (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l51">dictobject.h:51-56</a>).</li>
<li><p>The figure below is a logical representation of a Python hash table. In the figure below, <code>0, 1, ..., i, ...</code> on the left are indices of the <strong>slots</strong> in the hash table (they are just for illustrative purposes and are not stored along with the table obviously!).</p>
<pre><code># Logical model of Python Hash table
-+-----------------+
0| <hash|key|value>|
-+-----------------+
1| ... |
-+-----------------+
.| ... |
-+-----------------+
i| ... |
-+-----------------+
.| ... |
-+-----------------+
n| ... |
-+-----------------+
</code></pre></li>
<li><p>When a new dict is initialized it starts with 8 <em>slots</em>. (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l49">dictobject.h:49</a>)</p></li>
<li>When adding entries to the table, we start with some slot, <code>i</code>, that is based on the hash of the key. CPython initially uses <code>i = hash(key) & mask</code> (where <code>mask = PyDictMINSIZE - 1</code>, but that's not really important). Just note that the initial slot, i, that is checked depends on the <em>hash</em> of the key.</li>
<li>If that slot is empty, the entry is added to the slot (by entry, I mean, <code><hash|key|value></code>). But what if that slot is occupied!? Most likely because another entry has the same hash (hash collision!)</li>
<li>If the slot is occupied, CPython (and even PyPy) compares the <strong>the hash AND the key</strong> (by compare I mean <code>==</code> comparison not the <code>is</code> comparison) of the entry in the slot against the key of the current entry to be inserted (<a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l337">dictobject.c:337,344-345</a>). If <em>both</em> match, then it thinks the entry already exists, gives up and moves on to the next entry to be inserted. If either hash or the key don't match, it starts <strong>probing</strong>. </li>
<li>Probing just means it searches the slots by slot to find an empty slot. Technically we could just go one by one, <code>i+1, i+2, ...</code> and use the first available one (that's linear probing). But for reasons explained beautifully in the comments (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l33">dictobject.c:33-126</a>), CPython uses <strong>random probing</strong>. In random probing, the next slot is picked in a pseudo random order. The entry is added to the first empty slot. For this discussion, the actual algorithm used to pick the next slot is not really important (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Objects/dictobject.c#l33">dictobject.c:33-126</a> for the algorithm for probing). What is important is that the slots are probed until first empty slot is found.</li>
<li>The same thing happens for lookups, just starts with the initial slot i (where i depends on the hash of the key). If the hash and the key both don't match the entry in the slot, it starts probing, until it finds a slot with a match. If all slots are exhausted, it reports a fail.</li>
<li>BTW, the <code>dict</code> will be resized if it is two-thirds full. This avoids slowing down lookups. (see <a href="http://hg.python.org/cpython/file/52f68c95e025/Include/dictobject.h#l64">dictobject.h:64-65</a>)</li>
</ul>
<p>NOTE: I did the research on Python Dict implementation in response to my own <a href="http://stackoverflow.com/questions/9010222/">question</a> about how multiple entries in a dict can have same hash values. I posted a slightly edited version of the response here because all the research is very relevant for this question as well.</p>
| 241 | 2012-01-26T17:52:00Z | [
"python",
"data-structures",
"dictionary"
] |
storing unbound python functions in a class object | 327,483 | <p>I'm trying to do the following in python:</p>
<p>In a file called foo.py:</p>
<pre><code># simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
</code></pre>
<p>And then in a file called bar.py:
import foo</p>
<pre><code>d = foo.data
d.fn(1,2,3)
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)</p>
</blockquote>
<p>This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.</p>
<p>So the question is:</p>
<p><strong><em>How can I store a function in a class object without the function becoming bound to that class?</em></strong></p>
| 11 | 2008-11-29T12:21:47Z | 327,488 | <pre><code>data.fn = staticmethod(myFunction)
</code></pre>
<p>should do the trick.</p>
| 15 | 2008-11-29T12:28:33Z | [
"python",
"function"
] |
storing unbound python functions in a class object | 327,483 | <p>I'm trying to do the following in python:</p>
<p>In a file called foo.py:</p>
<pre><code># simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
</code></pre>
<p>And then in a file called bar.py:
import foo</p>
<pre><code>d = foo.data
d.fn(1,2,3)
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)</p>
</blockquote>
<p>This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.</p>
<p>So the question is:</p>
<p><strong><em>How can I store a function in a class object without the function becoming bound to that class?</em></strong></p>
| 11 | 2008-11-29T12:21:47Z | 327,491 | <p>This seems pointless to me. Why not just call myFunction when you need it?</p>
<p>In general, in Python, we use modules for this kind of namespacing (contrast this with Java where you just have no choice). And of course, myFunction is already bound to the module namespace when you define it.</p>
<p><a href="http://stackoverflow.com/questions/304655/the-best-way-to-invoke-methods-in-python-class-declarations">It is discussed somewhat in the answers to this question.</a></p>
| 0 | 2008-11-29T12:34:01Z | [
"python",
"function"
] |
storing unbound python functions in a class object | 327,483 | <p>I'm trying to do the following in python:</p>
<p>In a file called foo.py:</p>
<pre><code># simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
</code></pre>
<p>And then in a file called bar.py:
import foo</p>
<pre><code>d = foo.data
d.fn(1,2,3)
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)</p>
</blockquote>
<p>This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.</p>
<p>So the question is:</p>
<p><strong><em>How can I store a function in a class object without the function becoming bound to that class?</em></strong></p>
| 11 | 2008-11-29T12:21:47Z | 327,530 | <p>What you can do is:</p>
<pre><code>d = foo.data()
d.fn = myFunction
d.fn(1,2,3)
</code></pre>
<p>Which may not be exactly what you want, but does work.</p>
| 0 | 2008-11-29T13:38:20Z | [
"python",
"function"
] |
storing unbound python functions in a class object | 327,483 | <p>I'm trying to do the following in python:</p>
<p>In a file called foo.py:</p>
<pre><code># simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
</code></pre>
<p>And then in a file called bar.py:
import foo</p>
<pre><code>d = foo.data
d.fn(1,2,3)
</code></pre>
<p>However, I get the following error:</p>
<blockquote>
<p>TypeError: unbound method f() must be called with data instance as first argument (got int instance instead)</p>
</blockquote>
<p>This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition.</p>
<p>So the question is:</p>
<p><strong><em>How can I store a function in a class object without the function becoming bound to that class?</em></strong></p>
| 11 | 2008-11-29T12:21:47Z | 328,700 | <p>Thanks to Andre for the answer - so simple!</p>
<p>For those of you who care, perhaps I should have included the entire context of the problem. Here it is anyway:</p>
<p>In my application, users are able to write plugins in python. They must define a function with a well-defined parameter list, but I didn't want to impose any naming conventions on them.</p>
<p>So, as long as users write a function with the correct number of parameters and types, all they have to do is something like this (remember, this is the plugin code):</p>
<pre><code># this is my custom code - all plugins are called with a modified sys.path, so this
# imports some magic python code that defines the functions used below.
from specialPluginHelperModule import *
# define the function that does all the work in this plugin:
def mySpecialFn(paramA, paramB, paramC):
# do some work here with the parameters above:
pass
# set the above function:
setPluginFunction(mySpecialFn)
</code></pre>
<p>The call to <code>setPluginFunction</code> takes the function object and sets it in a hidden class object (along with other plugin-configuration related stuff, this example has been simplified somewhat). When the main application wants to run the function, I use the <code>runpy</code> module to run the plugin code, and then extract the class object mentioned above - this gives me the configuration data and the plugin function so I can run it cleanly (without polluting my namespace).</p>
<p>This entire process is repeated multiple times for different plugins over the same input, and seems to work very well for me.</p>
| 0 | 2008-11-30T10:21:24Z | [
"python",
"function"
] |
Storing and updating lists in Python dictionaries: why does this happen? | 327,534 | <p>I have a list of data that looks like the following:</p>
<pre><code>// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
</code></pre>
<p>... and I want to make this look like:</p>
<pre><code>0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
</code></pre>
<p>My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:</p>
<pre><code># where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
</code></pre>
<p>Now this causes IDLE to fail. However, if I do:</p>
<pre><code># code 2
d[t] = []
d[t].append(c)
</code></pre>
<p>... this works. </p>
<p>So the question is: why does code 2 work, but code 1 doesn't?</p>
<p>PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. </p>
| 19 | 2008-11-29T13:40:05Z | 327,548 | <p>Let's look at</p>
<pre><code>d[t].append(c)
</code></pre>
<p>What is the value of <code>d[t]</code>? Try it.</p>
<pre><code>d = {}
t = 0
d[t]
</code></pre>
<p>What do you get? Oh. There's nothing in <code>d</code> that has a key of <code>t</code>.</p>
<p>Now try this.</p>
<pre><code>d[t] = []
d[t]
</code></pre>
<p>Ahh. Now there's something in <code>d</code> with a key of <code>t</code>.</p>
<p>There are several things you can do. </p>
<ol>
<li>Use example 2.</li>
<li>Use <code>setdefault</code>. <code>d.setdefault(t,[]).append(c)</code>.</li>
<li>Use <a href="http://www.python.org/doc/2.5.2/lib/defaultdict-objects.html">collections.defaultdict</a>. You'd use a <code>defaultdict(list)</code> instead of a simple dictionary, <code>{}</code>.</li>
</ol>
<p><hr /></p>
<p><strong>Edit 1. Optimization</strong></p>
<p>Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex
list of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived.</p>
<pre><code>d= collections.defaultdict(list)
for ts, x, y in someFileOrListOrQueryOrWhatever:
d[ts].append( (x,y) )
</code></pre>
<p><hr /></p>
<p><strong>Edit 2. Answer Question</strong></p>
<p>"when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?"</p>
<p>I'm not sure what the question means. Since, all dictionaries <em>are</em> key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question.</p>
<p><strong>Example 2</strong>.</p>
<p>Initialization</p>
<pre><code>d= {}
</code></pre>
<p>Use</p>
<pre><code>if t not in d:
d[t] = list()
d[t].append( c )
</code></pre>
<p>Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list.</p>
<p><strong>Setdefault</strong></p>
<p>Initialization</p>
<pre><code>d= {}
</code></pre>
<p>Use</p>
<pre><code>d.setdefault(t,list()).append( c )
</code></pre>
<p>In this case, we exploit the <code>setdefault</code> method to either fetch a value associated with a key or create a new value associated with a missing key.</p>
<p><strong>default dict</strong></p>
<p>Initialization</p>
<pre><code>import collections
d = collections.defaultdict(list)
</code></pre>
<p>Use</p>
<pre><code>d[t].append( c )
</code></pre>
<p>The <code>defaultdict</code> uses an initializer function for missing keys. In this case, we provide the <code>list</code> function so that a new, empty list is created for a missing key.</p>
| 57 | 2008-11-29T13:46:42Z | [
"python",
"dictionary",
"list"
] |
Storing and updating lists in Python dictionaries: why does this happen? | 327,534 | <p>I have a list of data that looks like the following:</p>
<pre><code>// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
</code></pre>
<p>... and I want to make this look like:</p>
<pre><code>0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
</code></pre>
<p>My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:</p>
<pre><code># where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
</code></pre>
<p>Now this causes IDLE to fail. However, if I do:</p>
<pre><code># code 2
d[t] = []
d[t].append(c)
</code></pre>
<p>... this works. </p>
<p>So the question is: why does code 2 work, but code 1 doesn't?</p>
<p>PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. </p>
| 19 | 2008-11-29T13:40:05Z | 327,558 | <pre><code>dict=[] //it's not a dict, it's a list, the dictionary is dict={}
elem=[1,2,3]
dict.append(elem)
</code></pre>
<p>you can access the single element in this way:</p>
<pre><code>print dict[0] // 0 is the index
</code></pre>
<p>the output will be:</p>
<pre><code>[1, 2, 3]
</code></pre>
| 1 | 2008-11-29T13:53:34Z | [
"python",
"dictionary",
"list"
] |
Storing and updating lists in Python dictionaries: why does this happen? | 327,534 | <p>I have a list of data that looks like the following:</p>
<pre><code>// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
</code></pre>
<p>... and I want to make this look like:</p>
<pre><code>0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
</code></pre>
<p>My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:</p>
<pre><code># where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
</code></pre>
<p>Now this causes IDLE to fail. However, if I do:</p>
<pre><code># code 2
d[t] = []
d[t].append(c)
</code></pre>
<p>... this works. </p>
<p>So the question is: why does code 2 work, but code 1 doesn't?</p>
<p>PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. </p>
| 19 | 2008-11-29T13:40:05Z | 327,575 | <p>I think you want to use setdefault. It's a bit weird to use but does exactly what you need.</p>
<pre><code>d.setdefault(t, []).append(c)
</code></pre>
<p>The <code>.setdefault</code> method will return the element (in our case, a list) that's bound to the dict's key <code>t</code> if that key exists. If it doesn't, it will bind an empty list to the key <code>t</code> and return it. So either way, a list will be there that the <code>.append</code> method can then append the tuple <code>c</code> to.</p>
| 9 | 2008-11-29T14:28:09Z | [
"python",
"dictionary",
"list"
] |
Storing and updating lists in Python dictionaries: why does this happen? | 327,534 | <p>I have a list of data that looks like the following:</p>
<pre><code>// timestep,x_position,y_position
0,4,7
0,2,7
0,9,5
0,6,7
1,2,5
1,4,7
1,9,0
1,6,8
</code></pre>
<p>... and I want to make this look like:</p>
<pre><code>0, (4,7), (2,7), (9,5), (6,7)
1, (2,5), (4,7), (9,0), (6.8)
</code></pre>
<p>My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like:</p>
<pre><code># where t = 0, c = (4,7), d = {}
# code 1
d[t].append(c)
</code></pre>
<p>Now this causes IDLE to fail. However, if I do:</p>
<pre><code># code 2
d[t] = []
d[t].append(c)
</code></pre>
<p>... this works. </p>
<p>So the question is: why does code 2 work, but code 1 doesn't?</p>
<p>PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. </p>
| 19 | 2008-11-29T13:40:05Z | 332,525 | <p>In the case your data is not already sorted by desired criteria, here's the code that might help to group the data:</p>
<pre><code>#!/usr/bin/env python
"""
$ cat data_shuffled.txt
0,2,7
1,4,7
0,4,7
1,9,0
1,2,5
0,6,7
1,6,8
0,9,5
"""
from itertools import groupby
from operator import itemgetter
# load the data and make sure it is sorted by the first column
sortby_key = itemgetter(0)
data = sorted((map(int, line.split(',')) for line in open('data_shuffled.txt')),
key=sortby_key)
# group by the first column
grouped_data = []
for key, group in groupby(data, key=sortby_key):
assert key == len(grouped_data) # assume the first column is 0,1, ...
grouped_data.append([trio[1:] for trio in group])
# print the data
for i, pairs in enumerate(grouped_data):
print i, pairs
</code></pre>
<p>Output:</p>
<pre><code>0 [[2, 7], [4, 7], [6, 7], [9, 5]]
1 [[4, 7], [9, 0], [2, 5], [6, 8]]
</code></pre>
| 1 | 2008-12-01T22:54:25Z | [
"python",
"dictionary",
"list"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 327,601 | <p>You can use if...elif. If you have to choose a number, it would be like this:</p>
<pre><code>n = chosenOption()
if(n == 0):
doSomething()
elif(n == 1):
doAnyOtherThing()
else:
doDefaultThing()
</code></pre>
| 2 | 2008-11-29T15:06:14Z | [
"python"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 327,611 | <p>Have a look at this <a href="http://www.network-theory.co.uk/docs/pytut/ifStatements.html" rel="nofollow">topic</a> from "An Introduction to Python" book. Switch statement is substituted by an if..elif..elif sequence.</p>
| 2 | 2008-11-29T15:15:34Z | [
"python"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 327,612 | <p>Generally if elif will be fine, but if you have lots of cases, please consider using a dict.</p>
<pre><code>actions = {1: doSomething, 2: doSomethingElse}
actions.get(n, doDefaultThing)()
</code></pre>
| 5 | 2008-11-29T15:15:46Z | [
"python"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 327,735 | <p>To your first question I agree with Ali A.</p>
<p>To your second question :</p>
<p>import sys<br>
sys.exit(1)</p>
| 0 | 2008-11-29T17:27:51Z | [
"python"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 327,741 | <p>You might do something like this:</p>
<pre><code>def action1():
pass # put a function here
def action2():
pass # blah blah
def action3():
pass # and so on
def no_such_action():
pass # print a message indicating there's no such action
def main():
actions = {"foo": action1, "bar": action2, "baz": action3}
while True:
print_menu()
selection = raw_input("Your selection: ")
if "quit" == selection:
return
toDo = actions.get(selection, no_such_action)
toDo()
if __name__ == "__main__":
main()
</code></pre>
<p>This puts all your possible actions' functions into a dictionary, with the key being what you will input to run the function. It then retrieves the action input action from the list, unless the input action doesn't exist, in which case it retrieves no_such_action.</p>
<p>After you have a basic understanding of how this works, if you're considering doing a Serious Business command-lineâtype application, I would look at the <a href="http://docs.python.org/library/cmd.html"><code>cmd</code> framework</a> for command-line applications.</p>
| 12 | 2008-11-29T17:32:04Z | [
"python"
] |
Suggestion to implement a text Menu without switch case | 327,597 | <p>I'm giving my first steps on Python. I saw that we don't have switch case statement,
so I would you guys implement a text Menu in python?</p>
<p>Thanks</p>
| 2 | 2008-11-29T15:01:28Z | 9,634,208 | <p>I came here looking for the same thing and ended up writing my own:
<a href="https://github.com/gerrywastaken/menu.py" rel="nofollow">https://github.com/gerrywastaken/menu.py</a></p>
<p>You call it like so:</p>
<pre><code>import menu
message = "Your question goes here"
options = {
'f': ['[F]irst Option Name', 'First value'],
's': ['[S]econd Option Name', 'Second value'],
't': ['[T]hird Option Name', 'Third value']
}
selection = menu.getSelection(message, options)
</code></pre>
<p>It presents the user with a menu and they can select the option they want via the characters in the brackets. If they entered "s" as their option then selection would be assigned the value of 'Second Value'. I could have made it fancier, but I wanted to keep things simple, although pull requests are very welcome.</p>
| 0 | 2012-03-09T12:41:43Z | [
"python"
] |
Read the last lineof the file | 327,776 | <p>Imagine I have a file with </p>
<p>Xpto,50,30,60
Xpto,a,v,c
Xpto,1,9,0
Xpto,30,30,60</p>
<p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p>
<p>Thanks</p>
| 3 | 2008-11-29T18:03:03Z | 327,784 | <p>Not sure about a python specific implementation, but in a more language agnostic fashion, what you would want to do is skip (seek) to the end of the file, and then read each character in backwards order until you reach the line feed character that your file is using, usually a character with value 13. just read forward from that point to the end of the file, and you will have the last line in the file.</p>
| -1 | 2008-11-29T18:06:24Z | [
"python"
] |
Read the last lineof the file | 327,776 | <p>Imagine I have a file with </p>
<p>Xpto,50,30,60
Xpto,a,v,c
Xpto,1,9,0
Xpto,30,30,60</p>
<p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p>
<p>Thanks</p>
| 3 | 2008-11-29T18:03:03Z | 327,825 | <p>I think my answer from the <a href="http://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file-in-python">last time this came up</a> was sadly overlooked. :-)</p>
<blockquote>
<p>If you're on a unix box,
<code>os.popen("tail -10 " +
filepath).readlines()</code> will probably
be the fastest way. Otherwise, it
depends on how robust you want it to
be. The methods proposed so far will
all fall down, one way or another.
For robustness and speed in the most
common case you probably want
something like a logarithmic search:
use file.seek to go to end of the file
minus 1000 characters, read it in,
check how many lines it contains, then
to EOF minus 3000 characters, read in
2000 characters, count the lines, then
EOF minus 7000, read in 4000
characters, count the lines, etc.
until you have as many lines as you
need. But if you know for sure that
it's always going to be run on files
with sensible line lengths, you may
not need that.</p>
<p>You might also find some inspiration
in the <a href="http://www.koders.com/c/fid8DEE98A42C35A1346FA89C328CC3BF94E25CF377.aspx">source code</a> for the unix
<code>tail</code> command.</p>
</blockquote>
| 9 | 2008-11-29T18:34:42Z | [
"python"
] |
Read the last lineof the file | 327,776 | <p>Imagine I have a file with </p>
<p>Xpto,50,30,60
Xpto,a,v,c
Xpto,1,9,0
Xpto,30,30,60</p>
<p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p>
<p>Thanks</p>
| 3 | 2008-11-29T18:03:03Z | 327,980 | <p><code>f.seek( pos ,2)</code> seeks to 'pos' relative to the end of the file.
try a reasonable value for pos then readlines() and get the last line.</p>
<p>You have to account for when 'pos' is not a good guess, i.e. suppose you choose 300, but the last line is 600 chars long! in that case, just try again with a reasonable guess, until you capture the entire line. (this worst case should be very rare)</p>
| 1 | 2008-11-29T20:36:00Z | [
"python"
] |
Read the last lineof the file | 327,776 | <p>Imagine I have a file with </p>
<p>Xpto,50,30,60
Xpto,a,v,c
Xpto,1,9,0
Xpto,30,30,60</p>
<p>that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line?</p>
<p>Thanks</p>
| 3 | 2008-11-29T18:03:03Z | 10,180,739 | <p>Um why not just seek to the end of the file and read til you hit a newline?.</p>
<pre><code>i=0
while(1):
f.seek(i, 2)
c = f.read(1)
if(c=='\n'):
break
</code></pre>
| 0 | 2012-04-16T19:56:06Z | [
"python"
] |
Django equivalent for count and group by | 327,807 | <p>I have a model that looks like this:</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
</code></pre>
<p>I want select count (just the count) of items for each category, so in SQL it would be as simple as this:</p>
<pre><code>select category_id, count(id) from item group by category_id
</code></pre>
<p>Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the <em>count( )</em> method in Django, however I don't see how <em>group by</em> would fit there.</p>
| 82 | 2008-11-29T18:19:28Z | 327,987 | <p>(<strong>Update</strong>: Full ORM aggregation support is now included in <a href="http://docs.djangoproject.com/en/dev/releases/1.1/#aggregate-support">Django 1.1</a>. True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django. I haven't dug in to figure out why; if you're on 1.1 or later you should use the real <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/">aggregation API</a> anyway.)</p>
<p>The core aggregation support was already there in 1.0; it's just undocumented, unsupported, and doesn't have a friendly API on top of it yet. But here's how you can use it anyway until 1.1 arrives (at your own risk, and in full knowledge that the query.group_by attribute is not part of a public API and could change):</p>
<pre><code>query_set = Item.objects.extra(select={'count': 'count(1)'},
order_by=['-count']).values('count', 'category')
query_set.query.group_by = ['category_id']
</code></pre>
<p>If you then iterate over query_set, each returned value will be a dictionary with a "category" key and a "count" key.</p>
<p>You don't have to order by -count here, that's just included to demonstrate how it's done (it has to be done in the .extra() call, not elsewhere in the queryset construction chain). Also, you could just as well say count(id) instead of count(1), but the latter may be more efficient.</p>
<p>Note also that when setting .query.group_by, the values must be actual DB column names ('category_id') not Django field names ('category'). This is because you're tweaking the query internals at a level where everything's in DB terms, not Django terms.</p>
| 56 | 2008-11-29T20:44:21Z | [
"python",
"django"
] |
Django equivalent for count and group by | 327,807 | <p>I have a model that looks like this:</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
</code></pre>
<p>I want select count (just the count) of items for each category, so in SQL it would be as simple as this:</p>
<pre><code>select category_id, count(id) from item group by category_id
</code></pre>
<p>Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the <em>count( )</em> method in Django, however I don't see how <em>group by</em> would fit there.</p>
| 82 | 2008-11-29T18:19:28Z | 328,040 | <p>How's this? (Other than slow.)</p>
<pre><code>counts= [ (c, Item.filter( category=c.id ).count()) for c in Category.objects.all() ]
</code></pre>
<p>It has the advantage of being short, even if it does fetch a lot of rows.</p>
<p><hr /></p>
<p>Edit.</p>
<p>The one query version. BTW, this is often <em>faster</em> than SELECT COUNT(*) in the database. Try it to see.</p>
<pre><code>counts = defaultdict(int)
for i in Item.objects.all():
counts[i.category] += 1
</code></pre>
| 2 | 2008-11-29T21:31:53Z | [
"python",
"django"
] |
Django equivalent for count and group by | 327,807 | <p>I have a model that looks like this:</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
</code></pre>
<p>I want select count (just the count) of items for each category, so in SQL it would be as simple as this:</p>
<pre><code>select category_id, count(id) from item group by category_id
</code></pre>
<p>Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the <em>count( )</em> method in Django, however I don't see how <em>group by</em> would fit there.</p>
| 82 | 2008-11-29T18:19:28Z | 1,317,837 | <p>Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:</p>
<pre><code>from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))
</code></pre>
| 120 | 2009-08-23T05:21:09Z | [
"python",
"django"
] |
Django equivalent for count and group by | 327,807 | <p>I have a model that looks like this:</p>
<pre><code>class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
</code></pre>
<p>I want select count (just the count) of items for each category, so in SQL it would be as simple as this:</p>
<pre><code>select category_id, count(id) from item group by category_id
</code></pre>
<p>Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the <em>count( )</em> method in Django, however I don't see how <em>group by</em> would fit there.</p>
| 82 | 2008-11-29T18:19:28Z | 1,341,667 | <p>Since I was a little confused about how grouping in Django 1.1 works I thought I'd elaborate here on how exactly you go about using it. First, to repeat what Michael said:</p>
<blockquote>
<p>Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:</p>
<pre><code>from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))
</code></pre>
</blockquote>
<p>Note also that you need to <code>from django.db.models import Count</code>!</p>
<p>This will select only the categories and then add an annotation called <code>category__count</code>. Depending on the default ordering this may be all you need, <strong>but if the default ordering uses a field other than <code>category</code> this will not work</strong>. The reason for this is that the fields required for ordering are also selected and make each row unique, so you won't get stuff grouped how you want it. One quick way to fix this is to reset the ordering:</p>
<pre><code>Item.objects.values('category').annotate(Count('category')).order_by()
</code></pre>
<p>This should produce exactly the results you want. To set the name of the annotation you can use:</p>
<pre><code>...annotate(mycount = Count('category'))...
</code></pre>
<p>Then you will have an annotation called <code>mycount</code> in the results.</p>
<p>Everything else about grouping was very straightforward to me. Be sure to check out the <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation">Django aggregation API</a> for more detailed info.</p>
| 51 | 2009-08-27T15:02:17Z | [
"python",
"django"
] |
how to draw lines on a picture background in pygame | 327,896 | <p>I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.</p>
<p>Can anyone point me to some example code that does this?</p>
| 1 | 2008-11-29T19:31:42Z | 327,908 | <p>Help on module pygame.draw in pygame:</p>
<p>NAME
pygame.draw - pygame module for drawing shapes</p>
<p>FILE
d:\program files\python25\lib\site-packages\pygame\draw.pyd</p>
<p>FUNCTIONS
aaline(...)
pygame.draw.aaline(Surface, color, startpos, endpos, blend=1): return Rect
draw fine antialiased lines</p>
<pre><code>aalines(...)
pygame.draw.aalines(Surface, color, closed, pointlist, blend=1): return Rect
arc(...)
pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle, width=1): return Rect
draw a partial section of an ellipse
circle(...)
pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
draw a circle around a point
ellipse(...)
pygame.draw.ellipse(Surface, color, Rect, width=0): return Rect
draw a round shape inside a rectangle
line(...)
pygame.draw.line(Surface, color, start_pos, end_pos, width=1): return Rect
draw a straight line segment
lines(...)
pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
draw multiple contiguous line segments
polygon(...)
pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
draw a shape with any number of sides
rect(...)
pygame.draw.rect(Surface, color, Rect, width=0): return Rect
draw a rectangle shape
</code></pre>
| 0 | 2008-11-29T19:38:14Z | [
"python",
"drawing",
"pygame"
] |
how to draw lines on a picture background in pygame | 327,896 | <p>I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.</p>
<p>Can anyone point me to some example code that does this?</p>
| 1 | 2008-11-29T19:31:42Z | 328,002 | <p>This should do what you're asking for:</p>
<pre><code># load the image
image = pygame.image.load("some_image.png")
# draw a yellow line on the image
pygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100))
</code></pre>
<p>Typically you don't draw to the original image, since you'll have to reload the image to get the original back (or create a copy of it before you start drawing onto it). Perhaps what you actually need is something more like this:</p>
<pre><code># initialize pygame and screen
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 576))
# Draw the image to the screen
screen.blit(image, (0, 0))
# Draw a line on top of the image on the screen
pygame.draw.line(screen, (255, 255, 255), (0, 0), (50, 50))
</code></pre>
| 2 | 2008-11-29T20:59:44Z | [
"python",
"drawing",
"pygame"
] |
How do I modify the last line of a file? | 327,985 | <p>The last line of my file is:</p>
<blockquote>
<p>29-dez,40,</p>
</blockquote>
<p>How can I modify that line so that it reads:</p>
<blockquote>
<p>29-Dez,40,90,100,50</p>
</blockquote>
<p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p>
<p>I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.</p>
| 3 | 2008-11-29T20:41:28Z | 327,992 | <p>Don't work with files directly, make a data structure that fits your needs in form of a class and make read from/write to file methods.</p>
| 0 | 2008-11-29T20:46:52Z | [
"python",
"file"
] |
How do I modify the last line of a file? | 327,985 | <p>The last line of my file is:</p>
<blockquote>
<p>29-dez,40,</p>
</blockquote>
<p>How can I modify that line so that it reads:</p>
<blockquote>
<p>29-Dez,40,90,100,50</p>
</blockquote>
<p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p>
<p>I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.</p>
| 3 | 2008-11-29T20:41:28Z | 328,007 | <p>Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.</p>
<p>On the other hand maybe your file <em>is</em> really huge - multiple GBs at least. In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line. </p>
<p>So perhaps:</p>
<pre><code>f = open("foo.file", "wb")
f.seek(-len(os.linesep), os.SEEK_END)
f.write("new text at end of last line" + os.linesep)
f.close()
</code></pre>
<p>(Modulo line endings on different platforms)</p>
| 4 | 2008-11-29T21:05:31Z | [
"python",
"file"
] |
How do I modify the last line of a file? | 327,985 | <p>The last line of my file is:</p>
<blockquote>
<p>29-dez,40,</p>
</blockquote>
<p>How can I modify that line so that it reads:</p>
<blockquote>
<p>29-Dez,40,90,100,50</p>
</blockquote>
<p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p>
<p>I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.</p>
| 3 | 2008-11-29T20:41:28Z | 328,196 | <p>To expand on what <a href="http://stackoverflow.com/questions/327985/need-help-to-write-in-the-last-line-of-the-file#328007">Doug said</a>, in order to read the file contents into a data structure you can use the <a href="http://www.python.org/doc/2.5.2/lib/bltin-file-objects.html" rel="nofollow">readlines() method</a> of the file object.</p>
<p>The below code sample reads the file into a list of "lines", edits the last line, then writes it back out to the file: </p>
<pre><code>#!/usr/bin/python
MYFILE="file.txt"
# read the file into a list of lines
lines = open(MYFILE, 'r').readlines()
# now edit the last line of the list of lines
new_last_line = (lines[-1].rstrip() + ",90,100,50")
lines[-1] = new_last_line
# now write the modified list back out to the file
open(MYFILE, 'w').writelines(lines)
</code></pre>
<p>If the file is very large then this approach will not work well, because this reads all the file lines into memory each time and writes them back out to the file, which is very inefficient. For a small file however this will work fine. </p>
| 1 | 2008-11-29T23:41:59Z | [
"python",
"file"
] |
How do I modify the last line of a file? | 327,985 | <p>The last line of my file is:</p>
<blockquote>
<p>29-dez,40,</p>
</blockquote>
<p>How can I modify that line so that it reads:</p>
<blockquote>
<p>29-Dez,40,90,100,50</p>
</blockquote>
<p>Note: I don't want to write a new line. I want to take the same line and put new values after <code>29-Dez,40,</code></p>
<p>I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.</p>
| 3 | 2008-11-29T20:41:28Z | 339,388 | <p>I recently wrote a script to do something very similar to this. It would traverse a project, find all module dependencies and add any missing import statements. I won't clutter this post up with the entire script, but I'll show how I went about modifying my files.</p>
<pre><code>import os
from mmap import mmap
def insert_import(filename, text):
if len(text) < 1:
return
f = open(filename, 'r+')
m = mmap(f.fileno(), os.path.getsize(filename))
origSize = m.size()
m.resize(origSize + len(text))
pos = 0
while True:
l = m.readline()
if l.startswith(('import', 'from')):
continue
else:
pos = m.tell() - len(l)
break
m[pos+len(text):] = m[pos:origSize]
m[pos:pos+len(text)] = text
m.close()
f.close()
</code></pre>
<p>Summary: This snippet takes a filename and a blob of text to insert. It finds the last import statement already present, and sticks the text in at that location.</p>
<p>The part I suggest paying most attention to is the use of mmap. It lets you work with files in the same manner you may work with a string. Very handy.</p>
| 0 | 2008-12-04T01:52:50Z | [
"python",
"file"
] |
wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object | 328,003 | <p>If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with the user-input data from a spreadsheet widget, as in this example adapted from the tutorial on python.org:</p>
<pre><code>class ExSheet(wx.lib.sheet.CSheet):
def __init__(self, parent):
sheet.CSheet.__init__(self, parent)
self.SetLabelBackgroundColour('#CCFF66')
self.SetNumberRows(50)
self.SetNumberCols(50)
class Notebook(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
self.sheet1 = ExSheet(nb)
self.sheet2 = ExSheet(nb)
self.sheet3 = ExSheet(nb)
nb.AddPage(self.sheet1, "Sheet1")
nb.AddPage(self.sheet2, "Sheet2")
nb.AddPage(self.sheet3, "Sheet3")
self.sheet1.SetFocus()
self.StatusBar()
</code></pre>
| 3 | 2008-11-29T21:00:12Z | 328,078 | <p>Use a <a href="http://docs.wxwidgets.org/stable/wx_wxgrid.html" rel="nofollow">wxGrid</a> with a <a href="http://docs.wxwidgets.org/stable/wx_wxgridtablebase.html" rel="nofollow">wxGridTableBase</a> instead</p>
<p>Here is a simple example:</p>
<pre><code>import wx, wx.grid
class GridData(wx.grid.PyGridTableBase):
_cols = "a b c".split()
_data = [
"1 2 3".split(),
"4 5 6".split(),
"7 8 9".split()
]
def GetColLabelValue(self, col):
return self._cols[col]
def GetNumberRows(self):
return len(self._data)
def GetNumberCols(self):
return len(self._cols)
def GetValue(self, row, col):
return self._data[row][col]
def SetValue(self, row, col, val):
self._data[row][col] = val
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.data = GridData()
grid = wx.grid.Grid(self)
grid.SetTable(self.data)
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Show()
def OnClose(self, event):
print self.data._data
event.Skip()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()
</code></pre>
| 4 | 2008-11-29T22:14:09Z | [
"python",
"wxpython",
"spreadsheet",
"wx"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,066 | <p>I am not sure about Python but most languages have push/append function for arrays.</p>
| -5 | 2008-11-29T22:01:33Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,068 | <p>It's a lot easier than that:</p>
<pre><code>List = open("filename.txt").readlines()
</code></pre>
<p>This returns a list of each line in the file.</p>
| 38 | 2008-11-29T22:03:34Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,070 | <pre><code>my_list = [line.split(',') for line in open("filename.txt")]
</code></pre>
| 6 | 2008-11-29T22:06:14Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,072 | <p>A file is <em>almost</em> a list of lines. You can trivially use it in a <strong>for</strong> loop.</p>
<pre><code>myFile= open( "SomeFile.txt", "r" )
for x in myFile:
print x
myFile.close()
</code></pre>
<p>Or, if you want an actual list of lines, simply create a list from the file.</p>
<pre><code>myFile= open( "SomeFile.txt", "r" )
myLines = list( myFile )
myFile.close()
print len(myLines), myLines
</code></pre>
<p>You can't do <code>someList[i]</code> to put a <em>new</em> item at the end of a list. You must do <code>someList.append(i)</code>.</p>
<p>Also, <em>never</em> start a simple variable name with an uppercase letter. <code>List</code> confuses folks who know Python.</p>
<p>Also, <em>never</em> use a built-in name as a variable. <code>list</code> is an existing data type, and using it as a variable confuses folks who know Python.</p>
| 1 | 2008-11-29T22:06:39Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,073 | <p>f.readlines() returns a list that contains each line as an item in the list</p>
<p>if you want eachline to be split(",") you can use list comprehensions</p>
<pre><code>[ list.split(",") for line in file ]
</code></pre>
| 1 | 2008-11-29T22:07:14Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 328,074 | <p>Please read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a>. You're swaying pretty far from python conventions.</p>
<p>If you want a list of lists of each line split by comma, I'd do this:</p>
<pre><code>l = []
for line in in_file:
l.append(line.split(','))
</code></pre>
<p>You'll get a newline on each record. If you don't want that:</p>
<pre><code>l = []
for line in in_file:
l.append(line.rstrip().split(','))
</code></pre>
| 2 | 2008-11-29T22:07:40Z | [
"python"
] |
Create a List that contain each Line of a File | 328,059 | <p>I'm trying to open a file and create a list with each line read from the file.</p>
<pre><code> i=0
List=[""]
for Line in inFile:
List[i]=Line.split(",")
i+=1
print List
</code></pre>
<p>But this sample code gives me an error because of the <code>i+=1</code> saying that <code>index is out of range</code>.
What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?</p>
| 13 | 2008-11-29T21:55:53Z | 31,923,407 | <p>I did it this way</p>
<pre><code>lines_list = open('file.txt').read().splitlines()
</code></pre>
<p>Every line comes with its end of line characters (\n\r); this way the characters are removed.</p>
| 10 | 2015-08-10T15:22:21Z | [
"python"
] |
How to make a surface with a transparent background in pygame | 328,061 | <p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
| 18 | 2008-11-29T21:58:40Z | 328,067 | <p>This should do it:</p>
<pre><code>image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()
</code></pre>
<p>Make sure that the color depth (32) stays explicitly set else this will not work.</p>
| 20 | 2008-11-29T22:02:45Z | [
"python",
"transparency",
"pygame"
] |
How to make a surface with a transparent background in pygame | 328,061 | <p>Can someone give me some example code that creates a surface with a transparent background in pygame?</p>
| 18 | 2008-11-29T21:58:40Z | 353,739 | <p>You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:</p>
<pre><code>surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple
</code></pre>
<p>Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don't require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.</p>
| 8 | 2008-12-09T18:24:22Z | [
"python",
"transparency",
"pygame"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,110 | <p>Check if the cross product of <code>b-a</code> and <code>c-a</code> is<code>0</code>: that means all the points are collinear. If they are, check if <code>c</code>'s coordinates are between <code>a</code>'s and <code>b</code>'s. Use either the x or the y coordinates, as long as <code>a</code> and <code>b</code> are separate on that axis (or they're the same on both).</p>
<pre><code>def is_on(a, b, c):
"Return true iff point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
return (collinear(a, b, c)
and (within(a.x, c.x, b.x) if a.x != b.x else
within(a.y, c.y, b.y)))
def collinear(a, b, c):
"Return true iff a, b, and c all lie on the same line."
return (b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y)
def within(p, q, r):
"Return true iff q is between p and r (inclusive)."
return p <= q <= r or r <= q <= p
</code></pre>
<p>This answer used to be a mess of three updates. The worthwhile info from them: Brian Hayes's <a href="http://bit-player.org/bph-publications/BeautifulCode-2007-Hayes.pdf" rel="nofollow">chapter</a> in <em>Beautiful Code</em> covers the design space for a collinearity-test function -- useful background. <a href="http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment#328337">Vincent's answer</a> helped to improve this one. And it was Hayes who suggested testing only one of the x or the y coordinates; originally the code had <code>and</code> in place of <code>if a.x != b.x else</code>.</p>
| 24 | 2008-11-29T22:40:05Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,122 | <p>Check if the <strong>cross product</strong> of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.</p>
<p>But, as you want to know if c is between a and b, you also have to check that the <strong>dot product</strong> of (b-a) and (c-a) is <em>positive</em> and is <em>less</em> than the square of the distance between a and b.</p>
<p>In non-optimized pseudocode:</p>
<pre><code>def isBetween(a, b, c):
crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
if abs(crossproduct) > epsilon : return False # (or != 0 if using integers)
dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0 : return False
squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if dotproduct > squaredlengthba: return False
return True
</code></pre>
| 84 | 2008-11-29T22:46:45Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,126 | <p>The scalar product between (c-a) and (b-a) must be equal to the product of their lengths (this means that the vectors (c-a) and (b-a) are aligned and with the same direction). Moreover, the length of (c-a) must be less than or equal to that of (b-a). Pseudocode:</p>
<pre><code># epsilon = small constant
def isBetween(a, b, c):
lengthca2 = (c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y)
lengthba2 = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if lengthca2 > lengthba2: return False
dotproduct = (c.x - a.x)*(b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0.0: return False
if abs(dotproduct*dotproduct - lengthca2*lengthba2) > epsilon: return False
return True
</code></pre>
| 1 | 2008-11-29T22:51:43Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,142 | <p>Here's another approach: </p>
<ul>
<li>Lets assume the two points be A (x1,y1) and B (x2,y2)</li>
<li>The equation of the line passing through those points is (x-x1)/(y-y1)=(x2-x1)/(y2-y1) .. (just making equating the slopes)</li>
</ul>
<p>Point C (x3,y3) will lie between A & B if:</p>
<ul>
<li>x3,y3 satisfies the above equation.</li>
<li>x3 lies between x1 & x2 and y3 lies between y1 & y2 (trivial check)</li>
</ul>
| 4 | 2008-11-29T23:05:55Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,154 | <p>Using a more geometric approach, calculate the following distances:</p>
<pre><code>ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)
bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)
</code></pre>
<p>and test whether <strong>ac+bc</strong> equals <strong>ab</strong>:</p>
<pre><code>is_on_segment = abs(ac + bc - ab) < EPSILON
</code></pre>
<p>That's because there are three possibilities:</p>
<ul>
<li>The 3 points form a triangle => <strong>ac+bc > ab</strong></li>
<li>They are collinear and <strong>c</strong> is outside the <strong>ab</strong> segment => <strong>ac+bc > ab</strong></li>
<li>They are collinear and <strong>c</strong> is inside the <strong>ab</strong> segment => <strong>ac+bc = ab</strong></li>
</ul>
| 3 | 2008-11-29T23:14:32Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,193 | <p>Here's how I'd do it:</p>
<pre><code>def distance(a,b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)
def is_between(a,c,b):
return distance(a,c) + distance(c,b) == distance(a,b)
</code></pre>
| 26 | 2008-11-29T23:39:34Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,268 | <p>Here's how I did it at school. I forgot why it is not a good idea.</p>
<p>EDIT: </p>
<p>@Darius Bacon: <a href="http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment#328110">cites a "Beautiful Code" book</a> which contains an explanation why the belowed code is not a good idea.</p>
<pre><code>#!/usr/bin/env python
from __future__ import division
epsilon = 1e-6
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
class LineSegment:
"""
>>> ls = LineSegment(Point(0,0), Point(2,4))
>>> Point(1, 2) in ls
True
>>> Point(.5, 1) in ls
True
>>> Point(.5, 1.1) in ls
False
>>> Point(-1, -2) in ls
False
>>> Point(.1, 0.20000001) in ls
True
>>> Point(.1, 0.2001) in ls
False
>>> ls = LineSegment(Point(1, 1), Point(3, 5))
>>> Point(2, 3) in ls
True
>>> Point(1.5, 2) in ls
True
>>> Point(0, -1) in ls
False
>>> ls = LineSegment(Point(1, 2), Point(1, 10))
>>> Point(1, 6) in ls
True
>>> Point(1, 1) in ls
False
>>> Point(2, 6) in ls
False
>>> ls = LineSegment(Point(-1, 10), Point(5, 10))
>>> Point(3, 10) in ls
True
>>> Point(6, 10) in ls
False
>>> Point(5, 10) in ls
True
>>> Point(3, 11) in ls
False
"""
def __init__(self, a, b):
if a.x > b.x:
a, b = b, a
(self.x0, self.y0, self.x1, self.y1) = (a.x, a.y, b.x, b.y)
self.slope = (self.y1 - self.y0) / (self.x1 - self.x0) if self.x1 != self.x0 else None
def __contains__(self, c):
return (self.x0 <= c.x <= self.x1 and
min(self.y0, self.y1) <= c.y <= max(self.y0, self.y1) and
(not self.slope or -epsilon < (c.y - self.y(c.x)) < epsilon))
def y(self, x):
return self.slope * (x - self.x0) + self.y0
if __name__ == '__main__':
import doctest
doctest.testmod()
</code></pre>
| 1 | 2008-11-30T00:45:56Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,337 | <p>The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.</p>
<pre><code>class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Segment:
def __init__(self, a, b):
self.a = a
self.b = b
def is_between(self, c):
# Check if slope of a to c is the same as a to b ;
# that is, when moving from a.x to c.x, c.y must be proportionally
# increased than it takes to get from a.x to b.x .
# Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
# => c is after a and before b, or the opposite
# that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
# or 1 ( c == a or c == b)
a, b = self.a, self.b
return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and
abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)
</code></pre>
<p>Some random example of usage :</p>
<pre><code>a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)
print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)
</code></pre>
| 6 | 2008-11-30T01:58:59Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 328,647 | <p>Ok, lots of mentions of linear algebra (cross product of vectors) and this works in a real (ie continuous or floating point) space but the question specifically stated that the two points were expressed as <strong>integers</strong> and thus a cross product is not the correct solution although it can give an approximate solution.</p>
<p>The correct solution is to use <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm" rel="nofollow">Bresenham's Line Algorithm</a> between the two points and to see if the third point is one of the points on the line. If the points are sufficiently distant that calculating the algorithm is non-performant (and it'd have to be really large for that to be the case) I'm sure you could dig around and find optimisations.</p>
| 3 | 2008-11-30T08:56:44Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 329,347 | <p>how about just ensuring that the slope is the same and the point is between the others?</p>
<p>given points (x1, y1) and (x2, y2) ( with x2 > x1)
and candidate point (a,b)</p>
<p>if (b-y1) / (a-x1) = (y2-y2) / (x2-x1) And x1 < a < x2 </p>
<p>Then (a,b) must be on line between (x1,y1) and (x2, y2)</p>
| 0 | 2008-11-30T20:52:30Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 7,913,523 | <p>Any point on the line segment (<strong>a</strong>, <strong>b</strong>) (where <strong>a</strong> and <strong>b</strong> are vectors) can be expressed as a <em>linear combination</em> of the two vectors <strong>a</strong> and <strong>b</strong>:</p>
<p>In other words, if <strong>c</strong> lies on the line segment (<strong>a</strong>, <strong>b</strong>):</p>
<pre><code>c = ma + (1 - m)b, where 0 <= m <= 1
</code></pre>
<p>Solving for <em>m</em>, we get:</p>
<pre><code>m = (c.x - b.x)/(a.x - b.x) = (c.y - b.y)/(a.y - b.y)
</code></pre>
<p>So, our test becomes (in Python):</p>
<pre><code>def is_on(a, b, c):
"""Is c on the line segment ab?"""
def _is_zero( val ):
return -epsilon < val < epsilon
x1 = a.x - b.x
x2 = c.x - b.x
y1 = a.y - b.y
y2 = c.y - b.y
if _is_zero(x1) and _is_zero(y1):
# a and b are the same point:
# so check that c is the same as a and b
return _is_zero(x2) and _is_zero(y2)
if _is_zero(x1):
# a and b are on same vertical line
m2 = y2 * 1.0 / y1
return _is_zero(x2) and 0 <= m2 <= 1
elif _is_zero(y1):
# a and b are on same horizontal line
m1 = x2 * 1.0 / x1
return _is_zero(y2) and 0 <= m1 <= 1
else:
m1 = x2 * 1.0 / x1
if m1 < 0 or m1 > 1:
return False
m2 = y2 * 1.0 / y1
return _is_zero(m2 - m1)
</code></pre>
| 0 | 2011-10-27T08:42:26Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 9,224,700 | <p>c#
From <a href="http://www.faqs.org/faqs/graphics/algorithms-faq/" rel="nofollow">http://www.faqs.org/faqs/graphics/algorithms-faq/</a>
-> Subject 1.02: How do I find the distance from a point to a line?</p>
<pre><code>Boolean Contains(PointF from, PointF to, PointF pt, double epsilon)
{
double segmentLengthSqr = (to.X - from.X) * (to.X - from.X) + (to.Y - from.Y) * (to.Y - from.Y);
double r = ((pt.X - from.X) * (to.X - from.X) + (pt.Y - from.Y) * (to.Y - from.Y)) / segmentLengthSqr;
if(r<0 || r>1) return false;
double sl = ((from.Y - pt.Y) * (to.X - from.X) - (from.X - pt.X) * (to.Y - from.Y)) / System.Math.Sqrt(segmentLengthSqr);
return -epsilon <= sl && sl <= epsilon;
}
</code></pre>
| 0 | 2012-02-10T08:16:16Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 11,588,038 | <p>I needed this for javascript for use in an html5 canvas for detecting if the users cursor was over or near a certain line. So I modified the answer given by Darius Bacon into coffeescript:</p>
<pre><code>is_on = (a,b,c) ->
# "Return true if point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
return (collinear(a,b,c) and withincheck(a,b,c))
withincheck = (a,b,c) ->
if a[0] != b[0]
within(a[0],c[0],b[0])
else
within(a[1],c[1],b[1])
collinear = (a,b,c) ->
# "Return true if a, b, and c all lie on the same line."
((b[0]-a[0])*(c[1]-a[1]) < (c[0]-a[0])*(b[1]-a[1]) + 1000) and ((b[0]-a[0])*(c[1]-a[1]) > (c[0]-a[0])*(b[1]-a[1]) - 1000)
within = (p,q,r) ->
# "Return true if q is between p and r (inclusive)."
p <= q <= r or r <= q <= p
</code></pre>
| 2 | 2012-07-20T23:08:11Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 13,323,946 | <p>Here's a different way to go about it, with code given in C++. Given two points, l1 and l2 it's trivial to express the line segment between them as</p>
<pre><code>l1 + A(l2 - l1)
</code></pre>
<p>where 0 <= A <= 1. This is known as the vector representation of a line if you're interested any more beyond just using it for this problem. We can split out the x and y components of this, giving:</p>
<pre><code>x = l1.x + A(l2.x - l1.x)
y = l1.y + A(l2.y - l1.y)
</code></pre>
<p>Take a point (x, y) and substitute its x and y components into these two expressions to solve for A. The point is on the line if the solutions for A in both expressions are equal and 0 <= A <= 1. Because solving for A requires division, there's special cases that need handling to stop division by zero when the line segment is horizontal or vertical. The final solution is as follows:</p>
<pre><code>// Vec2 is a simple x/y struct - it could very well be named Point for this use
bool isBetween(double a, double b, double c) {
// return if c is between a and b
double larger = (a >= b) ? a : b;
double smaller = (a != larger) ? a : b;
return c <= larger && c >= smaller;
}
bool pointOnLine(Vec2<double> p, Vec2<double> l1, Vec2<double> l2) {
if(l2.x - l1.x == 0) return isBetween(l1.y, l2.y, p.y); // vertical line
if(l2.y - l1.y == 0) return isBetween(l1.x, l2.x, p.x); // horizontal line
double Ax = (p.x - l1.x) / (l2.x - l1.x);
double Ay = (p.y - l1.y) / (l2.y - l1.y);
// We want Ax == Ay, so check if the difference is very small (floating
// point comparison is fun!)
return fabs(Ax - Ay) < 0.000001 && Ax >= 0.0 && Ax <= 1.0;
}
</code></pre>
| 2 | 2012-11-10T16:48:59Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 19,633,299 | <p>Here is some Java code that worked for me:</p>
<pre><code>boolean liesOnSegment(Coordinate a, Coordinate b, Coordinate c) {
double dotProduct = (c.x - a.x) * (c.x - b.x) + (c.y - a.y) * (c.y - b.y);
if (dotProduct < 0) return true;
return false;
}
</code></pre>
| 1 | 2013-10-28T11:15:30Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 21,453,970 | <p>An answer in C# using a Vector2D class</p>
<pre><code>public static bool IsOnSegment(this Segment2D @this, Point2D c, double tolerance)
{
var distanceSquared = tolerance*tolerance;
// Start of segment to test point vector
var v = new Vector2D( @this.P0, c ).To3D();
// Segment vector
var s = new Vector2D( @this.P0, @this.P1 ).To3D();
// Dot product of s
var ss = s*s;
// k is the scalar we multiply s by to get the projection of c onto s
// where we assume s is an infinte line
var k = v*s/ss;
// Convert our tolerance to the units of the scalar quanity k
var kd = tolerance / Math.Sqrt( ss );
// Check that the projection is within the bounds
if (k <= -kd || k >= (1+kd))
{
return false;
}
// Find the projection point
var p = k*s;
// Find the vector between test point and it's projection
var vp = (v - p);
// Check the distance is within tolerance.
return vp * vp < distanceSquared;
}
</code></pre>
<p>Note that</p>
<pre><code>s * s
</code></pre>
<p>is the dot product of the segment vector via operator overloading in C#</p>
<p>The key is taking advantage of the projection of the point onto the infinite line and observing that the scalar quantity of the projection tells us trivially if the projection is on the segment or not. We can adjust the bounds of the scalar quantity to use a fuzzy tolerance.</p>
<p>If the projection is within bounds we just test if the distance from the point to the projection is within bounds.</p>
<p>The benefit over the cross product approach is that the tolerance has a meaningful value.</p>
| 0 | 2014-01-30T10:34:14Z | [
"python",
"math",
"geometry"
] |
How can you determine a point is between two other points on a line segment? | 328,107 | <p>Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point.</p>
<p>How can you determine if another point c is on the line segment defined by a and b?</p>
<p>I use python most, but examples in any language would be helpful.</p>
| 67 | 2008-11-29T22:37:13Z | 29,301,940 | <p>You can use the wedge and dot product:</p>
<pre><code>def dot(v,w): return v.x*w.x + v.y*w.y
def wedge(v,w): return v.x*w.y - v.y*w.x
def is_between(a,b,c):
v = a - b
w = b - c
return wedge(v,w) == 0 and dot(v,w) > 0
</code></pre>
| 0 | 2015-03-27T13:34:06Z | [
"python",
"math",
"geometry"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 328,374 | <p><a href="http://pypi.python.org/pypi/webstemmer/0.5.0" rel="nofollow">http://pypi.python.org/pypi/webstemmer/0.5.0</a></p>
<p><a href="http://atropine.sourceforge.net/documentation.html" rel="nofollow">http://atropine.sourceforge.net/documentation.html</a></p>
<p><hr /></p>
<p>alternatively, i think you can drive lynx from python, search on that</p>
| 4 | 2008-11-30T02:57:12Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 328,389 | <p><a href="http://www.aaronsw.com/2002/html2text/">html2text</a> is a Python program that does a pretty good job at this.</p>
| 69 | 2008-11-30T03:23:58Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 328,969 | <p>PyParsing does a great job. Paul McGuire has several scrips that are easy to adopt for various uses on the pyparsing wiki. (<a href="http://pyparsing.wikispaces.com/Examples">http://pyparsing.wikispaces.com/Examples</a>) One reason for investing a little time with pyparsing is that he has also written a very brief very well organized O'Reilly Short Cut manual that is also inexpensive.</p>
<p>Having said that, I use BeautifulSOup a lot and it is not that hard to deal with the entitites issues, you can convert them before you run BeautifulSoup. </p>
<p>Goodluck </p>
| 6 | 2008-11-30T15:46:19Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 1,463,802 | <p>You can use html2text method in the stripogram library also.</p>
<pre><code>from stripogram import html2text
text = html2text(your_html_string)
</code></pre>
<p>To install stripogram run sudo easy_install stripogram</p>
| 8 | 2009-09-23T03:21:58Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 3,987,802 | <p>Found myself facing just the same problem today. I wrote a very simple HTML parser to strip incoming content of all markups, returning the remaining text with only a minimum of formatting.</p>
<pre><code>from HTMLParser import HTMLParser
from re import sub
from sys import stderr
from traceback import print_exc
class _DeHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.__text = []
def handle_data(self, data):
text = data.strip()
if len(text) > 0:
text = sub('[ \t\r\n]+', ' ', text)
self.__text.append(text + ' ')
def handle_starttag(self, tag, attrs):
if tag == 'p':
self.__text.append('\n\n')
elif tag == 'br':
self.__text.append('\n')
def handle_startendtag(self, tag, attrs):
if tag == 'br':
self.__text.append('\n\n')
def text(self):
return ''.join(self.__text).strip()
def dehtml(text):
try:
parser = _DeHTMLParser()
parser.feed(text)
parser.close()
return parser.text()
except:
print_exc(file=stderr)
return text
def main():
text = r'''
<html>
<body>
<b>Project:</b> DeHTML<br>
<b>Description</b>:<br>
This small script is intended to allow conversion from HTML markup to
plain text.
</body>
</html>
'''
print(dehtml(text))
if __name__ == '__main__':
main()
</code></pre>
| 46 | 2010-10-21T13:14:38Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 8,201,491 | <p><strong>NOTE:</strong> NTLK no longer supports <code>clean_html</code> function</p>
<p>Original answer below.</p>
<hr>
<p>Use <a href="https://pypi.python.org/pypi/nltk">NLTK</a> </p>
<p>I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK.<br>
It works magically. </p>
<pre><code>import nltk
from urllib import urlopen
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
raw = nltk.clean_html(html)
print(raw)
</code></pre>
| 88 | 2011-11-20T12:34:09Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 9,357,137 | <p>Instead of the HTMLParser module, check out htmllib. It has a similar interface, but does more of the work for you. (It is pretty ancient, so it's not much help in terms of getting rid of javascript and css. You could make a derived class, but and add methods with names like start_script and end_style (see the python docs for details), but it's hard to do this reliably for malformed html.) Anyway, here's something simple that prints the plain text to the console</p>
<pre><code>from htmllib import HTMLParser, HTMLParseError
from formatter import AbstractFormatter, DumbWriter
p = HTMLParser(AbstractFormatter(DumbWriter()))
try: p.feed('hello<br>there'); p.close() #calling close is not usually needed, but let's play it safe
except HTMLParseError: print ':(' #the html is badly malformed (or you found a bug)
</code></pre>
| 4 | 2012-02-20T06:39:50Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 10,650,566 | <p>This isn't exactly a Python solution, but it will convert text Javascript would generate into text, which I think is important (E.G. google.com). The browser Links (not Lynx) has a Javascript engine, and will convert source to text with the -dump option.</p>
<p>So you could do something like:</p>
<pre><code>fname = os.tmpnam()
fname.write(html_source)
proc = subprocess.Popen(['links', '-dump', fname],
stdout=subprocess.PIPE,
stderr=open('/dev/null','w'))
text = proc.stdout.read()
</code></pre>
| 4 | 2012-05-18T10:02:26Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Extracting text from HTML file using Python | 328,356 | <p>I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. </p>
<p>I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.</p>
<p><strong>Update</strong> <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.</p>
<hr>
<p>Related questions:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/37486/filter-out-html-tags-and-resolve-entities-in-python">Filter out HTML tags and resolve entities in python</a></li>
<li><a href="http://stackoverflow.com/questions/57708/convert-xmlhtml-entities-into-unicode-string-in-python">Convert XML/HTML Entities into Unicode String in Python</a></li>
</ul>
| 128 | 2008-11-30T02:28:04Z | 13,633,210 | <p>There is Pattern library for data mining.</p>
<p><a href="http://www.clips.ua.ac.be/pages/pattern-web">http://www.clips.ua.ac.be/pages/pattern-web</a></p>
<p>You can even decide what tags to keep:</p>
<pre><code>s = URL('http://www.clips.ua.ac.be').download()
s = plaintext(s, keep={'h1':[], 'h2':[], 'strong':[], 'a':['href']})
print s
</code></pre>
| 6 | 2012-11-29T19:28:38Z | [
"python",
"html",
"text",
"html-content-extraction"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.