Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
Blenheim
Sep 22, 2010
Works like a charm; thanks.

Adbot
ADBOT LOVES YOU

FoiledAgain
May 6, 2007

Blenheim posted:

I don't know what terminology to use to do that, though. (I know that the current code is directing the value to be the first element in the list only.) Any help would be appreciated.

The term you're looking for is "slicing" or "slice notation".

spankweasel
Jan 4, 2006

Blenheim posted:

In my Python for Dummies class, we're doing an exercise where we compile a dictionary of terms from a text file and make a simple translator. The keys are all one-word, but the values vary from one word to several.

So:

code:
for line in FILE:
	pairs = line.split( 	)
	key = pairs[0]
	value = pairs[1]
	dct[key] = value
I need to say that the zeroth element in a line is the key and the rest, be it one word or several, is the value. I don't know what terminology to use to do that, though. (I know that the current code is directing the value to be the first element in the list only.) Any help would be appreciated.

str.split() can take an optional number of times to split the string.

In you case, you want something like:

code:
for line in FILE:
    key, value = line.split(None, 1)   # this means split on all white space but only split once
    dct[key] = value
>>> s = "this is a long string"
>>> s.split(None, 1)
['this', 'is a long string']

Optimus Prime Ribs
Jul 25, 2007

Does anyone know of a library for Python 3 that can make a "pretty" command line-type interface without involving any real GUI coding?
I ask because I'm making a text-based game as a way to learn Python, and the command prompt/Powershell in Windows is pretty drat ugly. I've looked at tkinter, which I can probably get to work, but if there is something that's already been made that'd be super.

spankweasel
Jan 4, 2006

Not sure if the cmd module would work for you or not. tkinter is more for building GUI things ...

http://docs.python.org/py3k/library/cmd.html#module-cmd

and

http://www.doughellmann.com/PyMOTW/cmd/

for examples.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
urwid?

Optimus Prime Ribs
Jul 25, 2007


This looks perfect but Python is giving me syntax errors for every string it uses because they're in the format u"foo".
Is that because I'm on Windows or do I just need to re-configure my Python install or something?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
It's made for Python 2. Run 2to3 on it.

Blenheim
Sep 22, 2010
ETA: Got the answer elsewhere; thanks anyhow.

Blenheim fucked around with this message at 14:31 on Jul 6, 2012

FoiledAgain
May 6, 2007

Blenheim posted:

Yeah, I know there's more to do, but my question concerns the error message I'm getting for the "text = text.replace(i, j)" line: "expected a character buffer object." Where am I screwing up in conjunction with this message?

Your dictionary values are lists (that's what j is, right?). You need to make them strings. I'd do it this way: text = text.replace(i, ''.join(j))

edit: actually, I think there's another problem because text = word.split() so it's a list too. Maybe you want to put that loop inside another for word in text?

double edit: no wait, you didn't pass words to the function, or do anything with it actually. Did you mean to create that?

FoiledAgain fucked around with this message at 09:05 on Jul 6, 2012

Optimus Prime Ribs
Jul 25, 2007

Suspicious Dish posted:

It's made for Python 2. Run 2to3 on it.

Well that worked, but now it's bitching about a missing termios module. I Googled it and apparently using cygwin would make it work, but it didn't (same error) so this is already becoming more cumbersome than I'd like; I'm just gonna stick to using Powershell.
Thanks anyways though. :)

Another question:

I read in this book that classes should always declared class Butts(object) instead of just class Butts to avoid possible headaches down the road.
How true is that? What could potentially happen if you don't explicitly say that it extends object?

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug

Optimus Prime Ribs posted:

I read in this book that classes should always declared class Butts(object) instead of just class Butts to avoid possible headaches down the road.
How true is that? What could potentially happen if you don't explicitly say that it extends object?

You can do more with new-style classes -- overriding method resolution order, adding descriptors, etc. A good description of what changed between old- and new-style classes can be found in the What's New in Python 2.2 section of the docs. You can also check out PEP 253.

This isn't really an issue for you, though; all classes are new-style classes in Python 3. You don't need to extend object anymore.

ufarn
May 30, 2009
I am trying to write a script that parses a document and does some Django stuff on it.

It's basically a manuscript with a title, author, list of characters, and occasional translator. This is the header, if you will. Then the dialogue follows with something like:

code:
ALICE
    Howdy

BOB
    Yo.

ALICE
    This example is the goddamn worst ever.

ME
    I know.
The header could be:

code:
AUTHOR
    ufarn

TITLE
    Alice & Bob
                
CHARACTERS
    Alice
    Bob
    Me
If we generalize the structure, you get something like this.

I haven't really played around in Python in a while, so I don't know how to attack this. I'd prefer if everything could be kept in one document, and I don't really want to get YAML involved. I want the practice of implementing this, too.

For the time being, I have your usual with f as open(...) and a subsequent for loop, but I don't really know where to go from there. I can hardcode checks for AUTHOR/TITLE/CHARACTERS and the occasional TRANSLATOR, and check for tabbed lines to grab the content and stop grabbing at \n. But I don't really have any good idea how to go about it, since I haven't done anything like this before.

Any suggestions?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
What you're doing so far sounds fine. Do you have any specific questions?

ufarn
May 30, 2009

Suspicious Dish posted:

What you're doing so far sounds fine. Do you have any specific questions?
Say the code uses the open ... for ... loop. What should I use to catch the parent elements?

Python code:
if line.rstrip() == "CHARACTERS":  # Or "TITLE", "AUTHOR", etc.
    # skip current line
    while line.startswith("    "):
        title = line.strip()
If I use the for loop like this, it doesn't work; I need to get from "CHARACTERS" to the next line so I can grab my values - same for all the other parents.

Can I skip forward in my `for` iteration without leaving my `if` conditional?

EDIT: I guess I could also generalize the script to creating a dict of the categories and an empty to be filled with character names, when CHARACTERS is parsed. That way, I can just create something like:

Python code:
if line.rstrip() in categories: 

elif line.rstrip() in characters:
I think I have an idea growing in my head. Still would like any suggestions.

EDIT Yup, getting close to something tangible. Woop.

ufarn fucked around with this message at 21:36 on Jul 6, 2012

tef
May 30, 2004

-> some l-system crap ->
Python code:
import collections


def parse_file(filename):
    with open(filename) as fh:
        return parse(fh)

def parse(fh):
    document = collections.OrderedDict()
    last_title = None
    for line in fh:
        if line.startswith('\t'):
            document[last_title].append(line.strip())

        else:
            line = line.strip()
            if line:
                last_title = line
                if last_title not in document:
                    document[last_title] = []
    return document
:toot:

ufarn
May 30, 2009
If I had to traverse a directory with a set of folders all with the file script.txt, how would I go about it? This is the last part that I think is tripping me up. I end up with three for loops along the lines of

Python code:
for root, dirs, files in os.walk(os.curdir):
  for name in files
      if name == "script.txt":
          create_django_objects("script.txt")
But that feels extremely cludgy.

I have never really had to do any I/O stuff that uses the os package, and this seems like the Python noobish way of going about it.

etcetera08
Sep 11, 2008

tef posted:

Python code:
import collections


def parse_file(filename):
    with open(filename) as fh:
        return parse(fh)

def parse(fh):
    document = collections.OrderedDict()
    last_title = None
    for line in fh:
        if line.startswith('\t'):
            document[last_title].append(line.strip())

        else:
            line = line.strip()
            if line:
                last_title = line
                if last_title not in document:
                    document[last_title] = []
    return document
:toot:

:3: I'm definitely stealing this skeleton if I have to do any bullshit parsing for classes next semester.

twerking on the railroad
Jun 23, 2007

Get on my level
I have a stupid @interact question. I have the following python (OK, really it's sage) code where I use a slider. The following code does almost everything I'd want to do, but I'd really prefer to not have a fixed increment of 1/120. Rather, I'd prefer to have yet another input box where I could enter a denominator which is an even integer N and have the slider's increment set to 1/N.

quote:

@interact
def _(t = slider(-1/2,1,1/120,0,'Value of your parameter t'), s = input_box(1,'Please enter the multiple s you would like to use',Integer)):
assert s != 0
print [1 + 2*t , 1 - t^2, t^2 + t + 1]
print [s*(1 + 2*t) , s*(1 - t^2), s*(t^2 + t + 1)]
print "Roots = "
print s*(1 + t - 2*t^2)/6, s*(1+ t)/2

Bonus points if you know how to put that program on a webpage!

ufarn
May 30, 2009
I found that post really hard to read, so here it is with syntax highlighting.

Python code:
(...)

ufarn fucked around with this message at 16:00 on Jul 7, 2012

twerking on the railroad
Jun 23, 2007

Get on my level
Python code:
@interact
 def _( t = slider(-1/2,1,1/120,0,'Value of your parameter t'), s = input_box(1,'Please enter the multiple s you would like to use',Integer)):
     assert s != 0
     print [1 + 2*t , 1 - t^2, t^2 + t + 1]
     print [s*(1 + 2*t) , s*(1 - t^2), s*(t^2 + t + 1)]
     print "Roots = "
     print s*(1 + t - 2*t^2)/6, s*(1+ t)/2
Thanks, perhaps this will be still easier to read

edit: I imagine the natural thing to do would be to have two interact functions, but for some reason, that doesn't seem to be working.

twerking on the railroad fucked around with this message at 16:11 on Jul 7, 2012

Cat Plus Plus
Apr 8, 2011

:frogc00l:

ufarn posted:

But that feels extremely cludgy.

If you want to see if script.txt exists in currently processed directory, and then do something on it, you don't really need that inner loop.

Python code:
for root, dirs, files in os.walk('.'):
    if 'script.txt' in files:
        # joining with root, so you can actually open it without changing
        # working directory
        path = os.path.join(root, 'script.txt')
        process_file(path)
Or in EAFP style, don't check for existence beforehand and just try to open it.

Python code:
for root, dirs, files in os.walk('.'):
    path = os.path.join(root, 'script.txt')
    process_file(path) # IOErrors handled inside

ufarn
May 30, 2009
I am running into the error SyntaxError: can't assign to function call, when I try to run this test script:

Python code:
import os


PATH = os.path.join(os.curdir, "scripts")

def parse(script):
    with f as open(script, "r"):
        print f

for root, dirs, files in os.walk(PATH):
    for name in files:
        if name == "script.txt":
            parse("script.txt")
and variations thereof.

What am I cocking up?

tef
May 30, 2004

-> some l-system crap ->
with f as open(script, "r"):

with open(script, "r") as f:

variable comes last in an 'as'

ufarn
May 30, 2009

tef posted:

with f as open(script, "r"):

with open(script, "r") as f:

variable comes last in an 'as'
That was embarrassing. Thanks.

On another note, what is the IOError referred to in this:

Python code:
for root, dirs, files in os.walk('.'):
    path = os.path.join(root, 'script.txt')
    process_file(path) # IOErrors handled inside
Reason I'm asking is because this gives me an IOError:

Python code:
for root, dirs, files in os.walk(PATH):
    for name in files:
        if name == "script.txt":
            with open("script.txt", "r") as f:
                print f
"No such file or directory: "script.txt"". But since I only match for that name, it seems weird.

ufarn fucked around with this message at 20:22 on Jul 7, 2012

Cat Plus Plus
Apr 8, 2011

:frogc00l:

ufarn posted:

"No such file or directory: "script.txt"". But since I only match for that name, it seems weird.

IOError is an exception you get when an I/O operation (like opening a file) fails. You're trying to open "script.txt" in the current working directory, and it doesn't exist, that's why it raises IOError. Hence why I said you need to do

Python code:
os.path.join(root, 'script.txt')
to get a proper path to the file you want to open.

Example: you have a directory structure:
code:
foo
   - bar
   - baz
      - script.txt
You run the script in "foo" directory, it does "os.walk('.')", and then it descends into "foo/baz". You check whether the file exists there, and try to open it. But you can't do "open('script.txt')", you have to do "open('baz/script.txt')". That's what the "root" ("./baz" in this example) is for.

Cat Plus Plus fucked around with this message at 20:52 on Jul 7, 2012

ufarn
May 30, 2009
That was just the explanation I needed. I couldn't really figure out the kinks of what was the active directory. Thanks again (and again (and again?)).

the
Jul 18, 2004

by Cowcaster
Has anyone used the bisection method to solve a function in Python? I have to do it for a class for one function and I'm having difficulty following the pseudocode provided on Wikipedia.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
What are you having trouble with?

vikingstrike
Sep 23, 2007

whats happening, captain
I've never solved that method in python, but that seems like a pretty great beginner exercise. Can you post up what you have and we can help from there?

the
Jul 18, 2004

by Cowcaster

Suspicious Dish posted:

What are you having trouble with?


I'm doing a projectile problem where v0 = initial launch velocity, theta is launch angle, and k is a constant for the air resistance.

I'm given v0, theta, and k, and I have to solve both:

R = ( v0^2 / g ) * sin(2*theta) where R is the distance it will land

T = ((k*v0*sin(theta) + g) / g*k) * (1 - e^(k*T)) where T is the time it will take

T is a "transcendental equation" that I have to solve numerically with the bisection method.

I have no idea how to apply the bisection method.

edit: I'm not asking you to do my homework, but I'm having difficulty both understanding what the bisection method does and how I apply it to a practical situation like that. I mean, I don't even know what a and b are, so how can I use f(a) and f(b)?

the fucked around with this message at 03:56 on Jul 9, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

the posted:

edit: I'm not asking you to do my homework, but I'm having difficulty both understanding what the bisection method does and how I apply it to a practical situation like that. I mean, I don't even know what a and b are, so how can I use f(a) and f(b)?

You pick a guess that seems reasonable. These guesses can be -sys.max_int and +sys.max_int if you really desire, but you can often do better than that in a special case.

Hed
Mar 31, 2004

Fun Shoe
I need a Geo package that will allow me to do things like circumscribe a set of points in a polygon (or even a circle). Can anyone recommend a package to look at? Nothing seems that obvious in PyPI.

the posted:

Has anyone used the bisection method to solve a function in Python? I have to do it for a class for one function and I'm having difficulty following the pseudocode provided on Wikipedia.
In situations where I don't understand the algorithm as much I will try to solve it with pencil and paper and then mark down the steps I do explicitly so that I know what is needed. Once you understand it and can work an example or two, break it down into gross steps, and if you keep refining you'll end up with something like pseudocode that should be more obvious to implement.

http://www.sosmath.com/calculus/limcon/limcon07/limcon07.html
http://www2.lv.psu.edu/ojj/courses/cmpsc-201/numerical/bisection.html

the
Jul 18, 2004

by Cowcaster
edit:NM

the fucked around with this message at 01:29 on Jul 10, 2012

accipter
Sep 12, 2003

Hed posted:

I need a Geo package that will allow me to do things like circumscribe a set of points in a polygon (or even a circle). Can anyone recommend a package to look at? Nothing seems that obvious in PyPI.


Perhaps shapley?

Hed
Mar 31, 2004

Fun Shoe
Thanks, I'll take a look at that :)

Optimus Prime Ribs
Jul 25, 2007

Is there a way to import a specific method from a module, but keep the module name in the label?
For example, some way to do this:
code:
from re import match
But still be able to call it by re.match()?

OnceIWasAnOstrich
Jul 22, 2006

Optimus Prime Ribs posted:

Is there a way to import a specific method from a module, but keep the module name in the label?
For example, some way to do this:
code:
from re import match
But still be able to call it by re.match()?

code:
from re import match
import re
Assuming you want to be able to access it both as match() and re.match(). Otherwise obviously just import the package.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
edit: :argh:

import on it's own only accepts modules and packages.
You can choose the assigned name of the import with:
Python code:
from re import match
from re import match as another_name

another_name == match
But other than that, you import the whole package, or just the bits you need without a namespace.

Adbot
ADBOT LOVES YOU

Optimus Prime Ribs
Jul 25, 2007

OnceIWasAnOstrich posted:

code:
from re import match
import re
Assuming you want to be able to access it both as match() and re.match(). Otherwise obviously just import the package.

Isn't that the same as doing just import re?

The reason I'm asking is because a couple times now I've found I needed a single method from a module, but like keeping the module's name in the label to keep it more clear (i.e. I like doing re.match() instead of just match()).

Should I just say "gently caress it" and import the entire re module?
I've read that it's poor practice to import all willy-nilly like that, but I like having the re. in there.

Maluco Marinero posted:

import on it's own only accepts modules and packages.
You can choose the assigned name of the import with:
Python code:
from re import match
from re import match as another_name

another_name == match

This brings up more of a "how to write good Python" question: if I were to import that as re_match would that be considered something "taboo" or "un-Pythonic"?

  • Locked thread