[Tutor] Help on Software Design decisions

2016-11-28 Thread Juan C.
I'm a student and my university uses Moodle as their learning management
system (LMS). They don't have Moodle Web Services enabled and won't be
enabling it anytime soon, at least for students. The university programs
have the following structure, for example:

1. Bachelor's Degree in Computer Science (duration: 8 semesters)

1.1. Unit 01: Mathematics Fundamental (duration: 1 semester)
1.1.1. Algebra I (first 3 months)
1.1.2. Algebra II (first 3 months)
1.1.3. Calculus I (last 3 months)
1.1.4. Calculus II (last 3 months)
1.1.5. Unit Project (throughout the semester)

1.2. Unit 02: Programming (duration: 1 semester)
1.2.1. Programming Logic (first 3 months)
1.2.2. Data Modelling with UML (first 3 months)
1.2.3. Python I (last 3 months)
1.2.4. Python II (last 3 months)
1.2.5. Unit Project (throughout the semester)

Each course/project have a bunch of assignments + one final assignment.
This goes on, totalizing 8 (eight) units, which will make up for a 4-year
program. I have to build my own Moodle API to be consumed by my program,
currently I'm using 'requests' + 'bs4' to do the job. I'm not here for
coding help, instead I have some python software design doubts. Some
information I have in mind:

- I was thinking about having the following classes: Program, Unit, Course,
Assignment, User.
- User would handle auth + session, the rest is pretty straightforward,
program would handle programs, unit would handles units, and so on.
- Inside Program init there would be attributes title, id and units; inside
Unit init there would be attributes title, id and courses; inside Course
init there would be attributes title, id, due_date, submitted, grade.

Should I call the site using requests and do all the parsing for everything
using bs4 as soon as I create a new instance of User? For example:

user = User('john.smith', 'password')  # will get all data needed
user.program  # 

cs = user.program
cs.units  # , , etc.

prog = cs.units[1]
prog.assignments  # , , , , [...], 

as03 = cs.assignments[2]
as03.title  # ''Assignment 03"
as03.id  # 202
as03.due_date  # 2016-11-30T21:21:00+00:00 (ISO 8601)

Is this a good Pythonic design? If not, how could it be better?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python Queue

2016-11-26 Thread Joaquin Alzola

>I have below code but it is giving this error:
>AttributeError: Queue instance has no attribute 'taskdone'

>import threading
>from Queue import Queue

>def worker(q):
>while True:
>  dataset = q.get()
>  print("q is taken out")
>  q.taskdone()

Per documentation it is task_done (I suppose you are using python 3+)

https://docs.python.org/3.5/library/queue.html


This email is confidential and may be subject to privilege. If you are not the 
intended recipient, please do not copy or disclose its content but contact the 
sender immediately upon receipt.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python Queue

2016-11-26 Thread Anish Tambe
> AttributeError: Queue instance has no attribute 'taskdone'

Method name is task_done (not taskdone)

https://docs.python.org/2/library/queue.html#Queue.Queue.task_done
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python Queue

2016-11-26 Thread Alan Gauld via Tutor
On 26/11/16 09:07, anish singh wrote:

> I have below code but it is giving this error:
> AttributeError: Queue instance has no attribute 'taskdone'

Please post the full error not just a summary.

Also please post the actual code...

> import threading
> from Queue import Queue

I get an import error here with no module named Queue.
Which Queue module are you using? Or should it be
spelled queue?

> def worker(q):
> while True:
>   dataset = q.get()
>   print("q is taken out")
>   q.taskdone()

Assuming you meant the standard queue module then
that should be

q.task_done()

When you get an attribute error it's worth trying
dir() on the offending object:

>>> from queue import Queue as Q
>>> dir(Q)
, task_done,
>>> help(Q.task_done)
...

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with Python Queue

2016-11-26 Thread anish singh
I was just writing to read a file using popen and wanted to use queue along
with it.
I have below code but it is giving this error:
AttributeError: Queue instance has no attribute 'taskdone'

import threading
from Queue import Queue

def worker(q):
while True:
  dataset = q.get()
  print("q is taken out")
  q.taskdone()

def create_data(q):
print("Inside create data")
output = [1, 2, 3]
for i in output:
  print("Inside", i)
  print("queue is put")
  q.put(i)

if __name__ == '__main__':
q = Queue()
t = threading.Thread(target=worker, args=(q,))
t.daemon = True
t.start()
create_data(q)
q.join()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help please

2016-10-20 Thread Alan Gauld via Tutor
On 20/10/16 21:25, Karen Palladino wrote:

> I am new to python and programming for that matter. Basically, I don't know
> much at all. I have python on my p/c which was put there by a former
> co-worker who wrote a program that extracts bites of information to generate
> a report. The format of the text file used to extract the information has
> changed and therefore, the information is not be extracted and distributed
> properly. 
> 
>  
> 
> We are looking for someone to help fine tune the program, can anyone help
> us?

This list can help you learn how to modify the program yourself,
but it is not a job board. So if you are trying to find a
programmer who can modify the program for you, you need to
look somewhere else. (There are several; sites that specialize
in Python jobs)

If you do want to learn how to program in Python then there are
many tutorials available for complete beginners (including mine,
see below)

There is a list here:

https://wiki.python.org/moin/BeginnersGuide/NonProgrammers

If you go down that route feel free to post any questions
you may have here and we will try to answer them.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help please

2016-10-20 Thread Karen Palladino
HI,

 

I am new to python and programming for that matter. Basically, I don't know
much at all. I have python on my p/c which was put there by a former
co-worker who wrote a program that extracts bites of information to generate
a report. The format of the text file used to extract the information has
changed and therefore, the information is not be extracted and distributed
properly. 

 

We are looking for someone to help fine tune the program, can anyone help
us?

 

Thank you,

 

Karen Palladino

The Windham Group, Inc.

363 West 22 Street

New York, NY   10011

212-624-1132

 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help regarding reg exp.

2016-10-05 Thread Danny Yoo
> On 05/10/16 10:03, rakesh sharma wrote:
>> Hi all
>>
>> I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}.
>

On Wed, Oct 5, 2016 at 3:14 AM, Alan Gauld via Tutor  wrote:
> Until we understand the data better we can't be sure
> a regex is the best solution.


Yes, I agree with Alan: we need to know more about the problem.

You've given one example.  Do you have a few more examples to give?
Why is your input a string, and not a structured object?  Where does
this input come from?


Generalizing a solution from an example set of size one is trivially
easy.  It doesn't need regexes or anything: it just needs a simple
string comparison:

###
def solution(input):
if input == "({A,BC},{(A,B),(B,C)(C,A)}":
return "{A,B,C}"
###

You might think that I'm joking.  This is a "ha, ha, just serious"
sort of thing.  In fact, this is exactly the first implementation I
would write if I were writing in test-driven-development mode.  It
forces me to write good test cases that actually exercise the solution
and to make sure I don't cheat like this.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help regarding reg exp.

2016-10-05 Thread Alan Gauld via Tutor
On 05/10/16 10:03, rakesh sharma wrote:
> Hi all
> 
> I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}. 

I'm not sure what you mean, can you send some real
examples of the data rather than just a generic pattern?

For example what do A,B and C signify? Are they literals?
Are they uppercase letters? Constant tokens? Something else?

> I want to extract the inner brackets {A,B,C} etc. 

You don't have a pattern like that in your string.
Do you mean the first term {A,BC}?
And should it really be {A,B,C}?

> Please help. I have tried various methods of re to no avail.

Until we understand the data better we can't be sure
a regex is the best solution.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help regarding reg exp.

2016-10-05 Thread rakesh sharma
Hi all

I have a string of pattern ({A,BC},{(A,B),(B,C)(C,A)}. I want to extract the 
inner brackets {A,B,C} etc. Please help. I have tried various methods of re to 
no avail.


Get Outlook for Android
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help!!

2016-09-27 Thread Alan Gauld via Tutor
On 26/09/16 23:50, Shooby Herrmann wrote:

> I am using JES.  

I've never heard of JES and know nothing about it.
Fortunately it doesn't look like this problem has much
to do with JES so that's not a problem this time...

However in future when you submit a question (whether
on this list or anywhere else) it will help immensely
if you tell us what the problem is. What output did
you expect? What did you get?

If you get an error show us the full error message.
Also tell us the Python version and OS you are using.
It all helps us to help you.

In this case it looks like a basic error so we can
probably help without the extra details...

> #The purpose of this assignment is to give you practice in function calls
> and if statements. Your program will have the user
> #to draw a random circle and a random rectangle and to guess which shape has
> more pixels. It will time how long the user
> #takes to do this and will connect the circle, the rectangle, and the
> outline of the picture with colored lines. 

all the drawing stuff

>   #Ask the user, "Which one has more pixels (type 'r' or 'c')?"
> 
>   info= requestString("Which one has more pixels? (type r or c).")
> 

So info will contain a character - either 'r' or 'c'

>   if info== (numPxRectangle >= numPxCircle) :

But you are comparing that character to the result of
a boolean comparison. Basically you are asking one of:

if 'c' == True:
if 'c' == False:
if 'r' == True:
if 'r' == False:

None of which makes much sense, so Python returns
False in every case.

> showInformation("Congradulations!")

So that line never gets executed.

You need to change the code so you can determine whether
the correct answer is 'c' or 'r' and then compare that
to the users input.

Also notice you were asked to time the user, you still need
to add code for that. But for now, focus on getting the
logic bit right.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help!!

2016-09-27 Thread Shooby Herrmann
Hi,

I am using JES.  I need to write a program and find all pixels in a circle
and in a square. Here is what I have written with the more detailed purpose
of the program.  I know this is not correct, but I'm not sure how to fix it.
Please help.

 

#The purpose of this assignment is to give you practice in function calls
and if statements. Your program will have the user

#to draw a random circle and a random rectangle and to guess which shape has
more pixels. It will time how long the user

#takes to do this and will connect the circle, the rectangle, and the
outline of the picture with colored lines. 

from random import*

def main():

  #Make an empty white 500x500 picture.

  pic= makeEmptyPicture(500, 500, white)

  #Assign variable radius to random value from 10 to 120 (Why this range?).

  radius= randrange(10, 121)

  xCircle= randrange(0, 501)

  yCircle= randrange(0, 501)

  #Draw a circle with this radius anywhere in the picture - show the whole
circle inside the picture.

  circle= addOvalFilled(pic, xCircle, yCircle, radius, radius)

  #Assign the variable numPxCircle to the number of pixels in this circle.

  numPxCircle= getPixels(pic)

  #Assign variables x and y to random values from 5 to 200 (Why this
range?).

  x= randrange(5, 201)

  y= randrange(5, 201)

  #Assign variables width and height to random values.

  # - find the ranges of the values that will show the whole rectangle
inside the picture.

  w= randrange(0, 501)

  h= randrange(0, 501)

  #Draw a green rectangle at the position (x,y) with this width and height
on the picture:

  # - (x, y) is the upper left-hand corner of the rectangle.

  #Assign the variable numPxRectangle to the number of pixels in this
rectangle.

  rectangle= addRectFilled(pic, x, y, w, h, green)

  numPxRectangle= getPixels(pic)

  #Show the picture.

  show(pic)

  #Ask the user, "Which one has more pixels (type 'r' or 'c')?"

  info= requestString("Which one has more pixels? (type r or c).")

  #If the answer is correct, fill the circle with red and pop up an
information box saying "Congratulations!".

  if info== (numPxRectangle >= numPxCircle) :

showInformation("Congradulations!")

  #If the answer is incorrect, pop up an information box saying "Sorry.
Bye!"

  #(Make sure that the full circle and the full square are shown inside the
picture.)

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with Numpy

2016-09-22 Thread Oscar Benjamin
On 22 September 2016 at 04:47, eryk sun  wrote:
> On Wed, Sep 21, 2016 at 10:35 PM, Oscar Benjamin
>  wrote:
>> I would have given the same advice a year or so ago. It's worth noting
>> though that the situation with pip, wheel etc has improved significantly
>> recently. It's now straightforward to pip install Numpy, scipy, matplotlib
>> and many others on Windows, OSX and Linux. Try it!
>
> There are NumPy and Matplotlib wheels for Windows on PyPI, but not for
> SciPy. Building SciPy from source on Windows is not straightforward.
> If you try to build with just VS 2015 installed, it fails because the
> required LAPACK/BLAS libs aren't available, and there's no Fortran
> compiler (Intel MKL is not free). For Windows users, I recommend
> downloading the wheels for NumPy and SciPy from Gohlke's site -- or
> just use a batteries-included distro as Alan recommended.

Oh yes I forgot about that. So all combinations except Windows+scipy
are now working. I thought the mingwpy project would have solved this
by now but it looks to be stalled.

-- 
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with Numpy

2016-09-21 Thread eryk sun
On Wed, Sep 21, 2016 at 10:35 PM, Oscar Benjamin
 wrote:
> I would have given the same advice a year or so ago. It's worth noting
> though that the situation with pip, wheel etc has improved significantly
> recently. It's now straightforward to pip install Numpy, scipy, matplotlib
> and many others on Windows, OSX and Linux. Try it!

There are NumPy and Matplotlib wheels for Windows on PyPI, but not for
SciPy. Building SciPy from source on Windows is not straightforward.
If you try to build with just VS 2015 installed, it fails because the
required LAPACK/BLAS libs aren't available, and there's no Fortran
compiler (Intel MKL is not free). For Windows users, I recommend
downloading the wheels for NumPy and SciPy from Gohlke's site -- or
just use a batteries-included distro as Alan recommended.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with Numpy

2016-09-21 Thread Oscar Benjamin
On 21 Sep 2016 22:29, "Alan Gauld via Tutor"  wrote:
>
> On 21/09/16 15:53, Paul Dentinger wrote:
> > Hello,
> > Sorry for such a basic question, but I am trying to get Numpy to work.
I
> > have python 3.5 and working in IDLE.  I need Numpy and Scipy and may
need
> > matplotlib.
>
> To be honest while you can install all the bits separately
> I normally recommend just getting a distro that already includes
> everything SciPy related.

I would have given the same advice a year or so ago. It's worth noting
though that the situation with pip, wheel etc has improved significantly
recently. It's now straightforward to pip install Numpy, scipy, matplotlib
and many others on Windows, OSX and Linux. Try it!

-- 
Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with Numpy

2016-09-21 Thread Alan Gauld via Tutor
On 21/09/16 15:53, Paul Dentinger wrote:
> Hello,
> Sorry for such a basic question, but I am trying to get Numpy to work.  I
> have python 3.5 and working in IDLE.  I need Numpy and Scipy and may need
> matplotlib. 

To be honest while you can install all the bits separately
I normally recommend just getting a distro that already includes
everything SciPy related.

Anaconda or Canopy are two that I can recommend.

https://www.continuum.io/downloads

https://store.enthought.com/downloads/#default

It just means that everything is there and although there
may be more than you need it saves any hassles with
dependencies etc.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with Numpy

2016-09-21 Thread eryk sun
On Wed, Sep 21, 2016 at 2:53 PM, Paul Dentinger  wrote:
>
> I need Numpy and Scipy and may need matplotlib.  So I tried to call Numpy and 
> it
> can't be found.  So I go online and find Numpy and download it.

Read the following docs on Python packaging and pip:

https://pip.pypa.io
https://packaging.python.org

I recommend Christoph Gohlke's MKL builds of NumPy and SciPy:

http://www.lfd.uci.edu/~gohlke/pythonlibs
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] help with Numpy

2016-09-21 Thread Paul Dentinger
Hello,
Sorry for such a basic question, but I am trying to get Numpy to work.  I
have python 3.5 and working in IDLE.  I need Numpy and Scipy and may need
matplotlib.  So I tried to call Numpy and it can't be found.  So I go
online and find Numpy and download it.  But because it's not an executable
installer, it's sitting in my downloads.  What I can't find is where to put
NumPy such that Python can find it when I call it?  I'm a little amazed
that I cannot find this.  Alternatively, if there is an executable
installer for these, I would appreciate it.

Thanks,
Paul
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-18 Thread Alan Gauld via Tutor
On 17/09/16 00:08, Sharon Wallace wrote:
> largest = None
> smallest = None
> 
> while True:
> num = raw_input('Enter a number:  ')
> if num = 'done' : break

should use == to test equality a single = is
an assignment and would give an error here

 print num
 try :
 num = float(inp)
 except :

Don't use a bare except here, specify the error,
otherwise you potentially miss a lot of useful
debug information. Specifically you want to
catch ValueError here.

 print 'Invalid input'
 continue

   if largest is None or num > largest :
  largest = num
   if smallest is None or num < smallest :
  smallest = num

> print 'Maximum is:', largest
> print 'Minimum is:', smallest

Fix those errors and it should work

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-17 Thread Alan Gauld via Tutor
On 17/09/16 00:08, Sharon Wallace wrote:
> inp = raw_input
> largest = None
> smallest = None
> 
> while True:
> num = raw_input('Enter a number:  ')
> if num = 'done' : break
> print num
> try :
> num = float(inp)
> except :
> print 'Invalid input'
> continue


While some whitespace is good, too much is as bad as none.
I've removed most of the blank lines but your indentation
levels are way too big. Also they are inconsistent and
in some places wrong. Indentation is crucially important
in Python.

Your code above should look like:

largest = None
smallest = None

while True:
num = raw_input('Enter a number:  ')
if num = 'done' :
break
print num
try :
num = float(inp)
except :
print 'Invalid input'
continue

That uses the recommended 4 spaces indentation and makes it
much easier to see what is going on.


hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-17 Thread Bob Gailer
On Sep 17, 2016 4:55 PM, "Sharon Wallace"  wrote:
>
> Would you please help me with the last piece of this assignment?
>
>
>
> This is my code:
>
>
>
> largest = None
>
> smallest = None
>
>
>
> while True:
>
> num = raw_input("Enter a number:  ")
>
> if num == "done" : break
>
> print num
>
>
>
> try :
>
> num = int(num)
>
> except :
>
> print "Invalid input"
>
> continue
>
>
>
> if num > largest :

> comparing integers To None is not a good idea. Your earlier program had
it right when you tested for None and greater than /  less then.

Another way to tackle this is to initialize largest to some extremely large
negative value and I smallest to some extremely large positive value.

When replying to these emails please always include the tutor group.

Congratulations on persisting and making it this far.

> largest = num
>
>
>
> if num < smallest :
>
> smallest = num
>
>
>
> print 'Maximum is', largest
>
> print 'Minimum is', smallest
.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-16 Thread Bob Gailer
On Sep 16, 2016 8:12 PM, "Sharon Wallace"  wrote:
>
In addition to showing us your code ,
Please show us whatever Trace back you got when you ran the code. I would
guess you are either getting an indentation error or syntax error in the
vicinity of line that begins if num =.

> inp = raw_input
>
> largest = None
>
> smallest = None
>
>
>
> while True:
>
> num = raw_input('Enter a number:  ')
>
> if num = 'done' : break
>
> print num
>
>
>
> try :
>
> num = float(inp)
>
> except :
>
> print 'Invalid input'
>
> continue
>
>
>
> if largest is None or num > largest :
>
> largest = num
>
>
>
> if smallest is None or num < smallest :
>
> smallest = num
>
>
>
> print 'Maximum is:', largest
>
> print 'Minimum is:', smallest
>
>
>
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Max Number and Min number script

2016-09-16 Thread Joel Goldstick
On Fri, Sep 16, 2016 at 7:08 PM, Sharon Wallace
 wrote:
> inp = raw_input

The above doesn't do what you think.  It creates a name called inp
which is bound to the function raw_input
>
> largest = None
>
> smallest = None
>
>
>
> while True:
>
> num = raw_input('Enter a number:  ')
>
> if num = 'done' : break
>
> print num
>
>
>
> try :
>
> num = float(inp)
>
> except :
>
> print 'Invalid input'
>
> continue
>
>
>
> if largest is None or num > largest :
>
> largest = num
>
>
>
> if smallest is None or num < smallest :
>
> smallest = num
>
>
>
> print 'Maximum is:', largest
>
> print 'Minimum is:', smallest
>
>
>

What is your question?  What works, or doesn't work?
>
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with Max Number and Min number script

2016-09-16 Thread Sharon Wallace
inp = raw_input

largest = None

smallest = None

 

while True:

num = raw_input('Enter a number:  ')

if num = 'done' : break

print num

 

try :

num = float(inp)

except :

print 'Invalid input'

continue

 

if largest is None or num > largest :

largest = num

 

if smallest is None or num < smallest :

smallest = num



print 'Maximum is:', largest

print 'Minimum is:', smallest

 

 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with NameError

2016-09-01 Thread Peter Otten
Bryan Callow wrote:

> Could someone help me with a NameError that I can't seem to figure out.
> The program asks for an input and then runs two DC motors.  It worked for
> a while and then when I reopened the program today I keep getting this
> error.  Thank you.  -Bryan

[...]
> print('Which direction would you like to move?')
> direction = input("Type 'f' for forward, 'b' for backward, or 'e' to exit:
> ")
> while direction not in exit_:
[...]

My crystal ball says:

Your script is written in Python 3, but you are trying to run it with Python 
2. 

Background: Python 2's input() function evaluates user input as a Python 
expression -- if for example you enter 1+1 input() will return 2; if you 
enter b input() will look up the variable b and fail with a NameError 
because no such variable exists. 

Run your script with 

$ python3 yourscript.py

and everything should work as expected. To avoid such confusion in the 
future you can insert

#!/usr/bin/env python3

as the first line, make the script executable with

$ chmod u+x yourscript.py

and run it with

$ ./yourscript.py

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with NameError

2016-09-01 Thread Alan Gauld via Tutor
On 01/09/16 02:29, Bryan Callow wrote:
> Could someone help me with a NameError that I can't seem to figure out.

It is hard for us to figure out without seeing the error message.
It should tell you which name is in error and where.

Please repost with the full error message included.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with NameError

2016-09-01 Thread Bryan Callow
Could someone help me with a NameError that I can't seem to figure out.
The program asks for an input and then runs two DC motors.  It worked for a
while and then when I reopened the program today I keep getting this
error.  Thank you.  -Bryan

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)

Motor1A = 16
Motor1B = 18
Motor1E = 22

Motor2A = 11
Motor2B = 13
Motor2E = 15

GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)

GPIO.setup(Motor2A,GPIO.OUT)
GPIO.setup(Motor2B,GPIO.OUT)
GPIO.setup(Motor2E,GPIO.OUT)

forward = ['f', 'F']
backward = ['b', 'B']
exit_ = ['e', 'E']

print('Which direction would you like to move?')
direction = input("Type 'f' for forward, 'b' for backward, or 'e' to exit:
")
while direction not in exit_:
if direction in forward:
print('Moving Forward!')
GPIO.output(Motor1A,GPIO.HIGH)
GPIO.output(Motor1B,GPIO.LOW)
GPIO.output(Motor1E,GPIO.HIGH)
GPIO.output(Motor2A,GPIO.HIGH)
GPIO.output(Motor2B,GPIO.LOW)
GPIO.output(Motor2E,GPIO.HIGH)
sleep(2)
print ("Stopping!")
GPIO.output(Motor1E,GPIO.LOW)
GPIO.output(Motor2E,GPIO.LOW)
if direction in backward:
print('Moving Backward!')
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
GPIO.output(Motor2A,GPIO.LOW)
GPIO.output(Motor2B,GPIO.HIGH)
GPIO.output(Motor2E,GPIO.HIGH)
sleep(2)
print ("Stopping!")
GPIO.output(Motor1E,GPIO.LOW)
GPIO.output(Motor2E,GPIO.LOW)
sleep(1)
print('Which direction would you like to move?')
direction = input("Type 'f' for forward, 'b' for backward, or 'e' to
exit: ")

print('done')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2016-08-04 Thread Peter Otten
CJ wrote:

> Hi,
>   I’m coding a game for fun and i keep trying to run it but this keeps
>   showing up:
> traceback (most recent call last):
>   File "/Volumes/name/box move thing(wed).py", line 13, in 
> player_img = PhotoImage(file="astronaut.png")
>   File
>   
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py",
>   line 3394, in __init__
> Image.__init__(self, 'photo', name, cnf, master, **kw)
>   File
>   
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py",
>   line 3350, in __init__
> self.tk.call(('image', 'create', imgtype, name,) + options)
> _tkinter.TclError: couldn't open "astronaut.png": no such file or
> directory
> 
> Even though I have a file named “astronaut.png” I’ve tried a lot of things
> if I could be helped that would be awesome.

Print the working directory before the line creating the image:

  import os
  os.print(os.getcwd())
> player_img = PhotoImage(file="astronaut.png")


Chances are that "astronaut.png" is in another directory. If so you have to 
provide the path to that directory, e. g.

player_img = PhotoImage(file="images/astronaut.png")

If the image is in the same directory as the script you can construct the 
path with

import os
image_folder = os.path.dirname(__file__)
...
player_img = PhotoImage(file=os.path.join(image_folder, "astronaut.png"))

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help

2016-08-04 Thread CJ
Hi,
  I’m coding a game for fun and i keep trying to run it but this keeps showing 
up:
traceback (most recent call last):
  File "/Volumes/name/box move thing(wed).py", line 13, in 
player_img = PhotoImage(file="astronaut.png")
  File 
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py",
 line 3394, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
  File 
"/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py",
 line 3350, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't open "astronaut.png": no such file or directory

Even though I have a file named “astronaut.png” I’ve tried a lot of things if I 
could be helped that would be awesome.


   Thanks,
   Anonymous
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help on Assignments - trivia game

2016-07-30 Thread Alan Gauld via Tutor
On 30/07/16 16:28, Justin Korn via Tutor wrote:

> trivia_game.py

> import sys
> import random
> import Question.py

You do not include the .py extension in an import
statement. It should read

import Question

Also by convention modules use lowercase names.

> questions = [
> Question("How many states start with the letter M", 3, ["6", "7", "8", 
> "9"]),

You are trying to instantiate a Question object but it is (presumably)
defined in the question.py class which you import. If so you need to
prefix it with the module name like so

Question.Question(...)

> Question("What is the area of a right triagle with a hypotenuse of 10 and 
> an altitude of 8", 1, ["24", "40", "48", "80"]), 
> Question("Which physics quantity is not a vector", 4, ["Acceleration", 
> "Momentum", "Torque", "Work"]),

List indices start from zero so your highest index should be 3.
Assuming you intend to use the '4' as an index to the correct answer?

> Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh 
> Steelers", "Minnesota Vikings", "Indianapolis Colts"])
> ]
> 
> 
> random.shuffle(questions)# Randomize the order of the questions
> 
> for question in questions:
> question.ask()
> 
> Question.py

???
I'm expecting a class definition here with at least
__init__() and ask() methods. And it needs to store
the question, possible answers and correct answer
somewhere too?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help on Assignments - Turtle

2016-07-30 Thread Alan Gauld via Tutor
On 30/07/16 16:28, Justin Korn via Tutor wrote:
> I have been working on these assignments for a week and a half, 
> and I can't make any progress. I also been dealing with a
> sick relative, so please help me out immediately.

While I sympathise with your circumstances we are all
volunteers here so the help you receive will be at the
speed that suits the members.

I will address your two assignments in separate mails.


> import turtle
> class turtle_Turtle():
> ts = turtle.Screen()
> ts.title("TurtleGTX")
> bob = turtle.Turtle()
> bob.shape("turtle")
> bob.color("brown")

I'm not sure what you think this is doing but I'm
pretty sure its not what you want. You are basically
defining a couple of class variables and nothing else...

> class TurtleGTX(turtle_Turtle):

I would have expected you to inherit from turtle.Turtle
rather than turtle_Turtle. The latter has no methods and
only two class variables. So your GTX class likewise has
no inherited methods, you will need to define all of
its behaviour.

> odometer = 0

This is a class variable meaning it is shared by all
turtles. I suspect you really want it to be an instance
attribute, which means defined within an __init__()


> def forward(x):

The first parameter of a class method is usually called
self because it will refer to the active object. In this
case your x will be the object, whereas I think you want
it to be the distance to move? But if so x is a bad choice
of name since it implies horizontal direction only

> if (x >= 0):
> i = 0
> while (i < x):
> self.fd()
> odometer += 1
> i+=1

This is a horribly inefficient way of saying

if x>=0:
  self.fd(x)
  odometer += x

But it won't work because
a) You didn't inherit from turtle so you don't have a fd() method
b) Even if you had it requires an input value for its distance
so should be self.fd(1)


> else:
> i = 0
> while (i > x):
> self.bk()
> odometer +=1
> i-=1

Again a very inefficient alternative to

else:
   x = -x
   self.bk(x)
   odometer += x

> print ("Odometer is", odemeter)

Do you really want to print that every time the turtle moves?

> my_turtle = TurtleGTX()
> my_turtle.foward()

You misspelled forward and failed to give it an x value.
Please send real code and/or any error messages. This code
could never have run so you should have errors.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help on Assignments

2016-07-30 Thread Justin Korn via Tutor
To whom it may concern, I need someone to help me to develop programs for the 
following assignments. I have been working on these assignments for a week and 
a half, and I can't make any progress. I also been dealing with a sick 
relative, so please help me out immediately. I use the version 3.4.1. Here are 
the following assignments and what I have so far:



1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: 
it can jump forward a given distance, and it has an odometer that keeps track 
of how far the turtle has travelled since it came off the production line. (The 
parent class has a number of synonyms like fd, forward, back, backward, and bk: 
for this exercise, just focus on putting this functionality into the forward 
method.) Think carefully about how to count the distance if the turtle is asked 
to move forward by a negative amount. (We would not want to buy a second-hand 
turtle whose odometer reading was faked because its previous owner drove it 
backwards around the block too often. Try this in a car near you, and see if 
the car’s odometer counts up or down when you reverse.)



import turtle
class turtle_Turtle():
ts = turtle.Screen()
ts.title("TurtleGTX")
bob = turtle.Turtle()
bob.shape("turtle")
bob.color("brown")

class TurtleGTX(turtle_Turtle):
odometer = 0
def forward(x):
if (x >= 0):
i = 0
while (i < x):
self.fd()
odometer += 1
i+=1
else:
i = 0
while (i > x):
self.bk()
odometer +=1
i-=1
print ("Odometer is", odemeter)


my_turtle = TurtleGTX()
my_turtle.foward()


2. You are to develop a program (name it trivia_game.py) that will play a 
trivia game with two players.  The game will be played this way:
Starting with player 1, each player gets a turn at answering 5 trivia 
questions.  When a question is displayed, 4 possible answers are also displayed 
(1 of the 4 is the correct answer).  A correct answer earns the player 1 point.
After both players have answered their 5 questions the program will display the 
number of points earned by each player and declare the player with the most 
points the winner (or a tie if both players have earned the same number of 
points).
You must write a class (name it Question.py) to hold the data for a trivia 
question.  The class should have the following attributes:

A trivia question
Possible answer 1
Possible answer 2
Possible answer 3
Possible answer 4
The number of the correct answer (1, 2, 3, or 4)
The Question class should have an appropriate __init__ method, accessors and 
mutators.

Your program should have a list or dictionary containing 10 Question objects, 
one for each trivia question. You are to make up your own trivia questions. 

Submit both files (zip the two files if possible).

trivia_game.py
import sys
import random
import Question.py

questions = [
Question("How many states start with the letter M", 3, ["6", "7", "8", 
"9"]),
Question("What is the area of a right triagle with a hypotenuse of 10 and 
an altitude of 8", 1, ["24", "40", "48", "80"]), 
Question("Which physics quantity is not a vector", 4, ["Acceleration", 
"Momentum", "Torque", "Work"]),
Question("How many inches are in a foot", 2, ["6", "12", "18", "24"]),
Question("Who does not play in the NFL anymore", 3, ["Frank Gore", "Richard 
Sherman", "Peyton Manning", "Antonio Gates"]),
Question("What is a bakers dozen equivalent to", 4, ["10", "11", "12", 
"13"]),
Question("Which city has a NBA team", 1, ["Sacramento", "Baltimore", "St. 
Louis", "Pittsburgh"]),
Question("Which of the following elements have eleven protons", 4, 
["boron", "sulfur", "floruine", "sodium"]),
Question("What is the minimum age to run for president of the United 
States", 2, ["30", "35", "40", "45"]),
Question("Who won super bowl 44", 1, ["New Orleans Saints", "Pittsburgh 
Steelers", "Minnesota Vikings", "Indianapolis Colts"])
]


random.shuffle(questions)# Randomize the order of the questions

for question in questions:
question.ask()

Question.py

3. Our final exam is a real world problem about efficiency in a warehouse.  

XYZ Corporation sells products online.  The company has a large warehouse in 
which it stores its inventory of products.  Orders are picked, packed and 
shipped from the warehouse.

XYZ Corporation has contracted with you to write a program that will minimize 
the number of steps that the staff in the warehouse (called ODA's) take in 
picking the products ordered by customers.

The information you will need to complete this assignment are in the following 
files:

Specifications: CTIM285_Summer_2016_FinalExam.pdf
Warehouse Map: WarehouseImage.pdf
Data for Analysis:  warehouse_data_final_exam_Python.txt
Data for Analysis is saved in this order on each line of the file:
[orderNumber, partNumber

Re: [Tutor] Help on Assginments

2016-07-30 Thread Alan Gauld via Tutor
On 30/07/16 05:31, Justin Korn via Tutor wrote:
> ...I need someone to help me to develop programs for the following 
> assignments:

That's not really how tutor list works.
We will answer your questions and give you hints when
you get stuck. But it is the whole list membership helping
you, not a designated "someone".

As to your projects here's what I'd recommend.

1) Tackle them one by one, it keeps the email threads
   separate and the archives easier to search.

2) Make a start, write some code. When you get stuck or
   something doesn't work as expected, ask here.

3) Always remind us of which OS and Python version you
   are using

4) If there are error messages send the whole error
   text not a summary.


> 1. Define a new kind of Turtle, ...

This one slightly confused me since the standard turtle
can already jump forward a given distance. The only new
feature appears to be the odometer concept?

> 2. You are to develop a program (name it trivia_game.py) that 
> will play a trivia game with two players.
...
> You must write a class (name it Question.py) to hold the data

This seems straightforward but a tad tedious creating the
data. It would have been nice if they provided a data file!

> Our final exam is a real world problem about efficiency in a warehouse.  

Slightly more challenging but nothing too difficult
provided you can do the math and the document provided
is sufficiently clear.


Based on the questions I assume you have a reasonably good understanding
of Python basics including the data structures, functions, classes and
objects, files, and how to import
and use modules?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help on Assginments

2016-07-30 Thread Justin Korn via Tutor
To whom it may concern, I need someone to help me to develop programs for the 
following assignments:



1. Define a new kind of Turtle, TurtleGTX, that comes with some extra features: 
it can jump forward a given distance, and it has an odometer that keeps track 
of how far the turtle has travelled since it came off the production line. (The 
parent class has a number of synonyms like fd, forward, back, backward, and bk: 
for this exercise, just focus on putting this functionality into the forward 
method.) Think carefully about how to count the distance if the turtle is asked 
to move forward by a negative amount. (We would not want to buy a second-hand 
turtle whose odometer reading was faked because its previous owner drove it 
backwards around the block too often. Try this in a car near you, and see if 
the car’s odometer counts up or down when you reverse.)

2. You are to develop a program (name it trivia_game.py) that will play a 
trivia game with two players.  The game will be played this way:
Starting with player 1, each player gets a turn at answering 5 trivia 
questions.  When a question is displayed, 4 possible answers are also displayed 
(1 of the 4 is the correct answer).  A correct answer earns the player 1 point.
After both players have answered their 5 questions the program will display the 
number of points earned by each player and declare the player with the most 
points the winner (or a tie if both players have earned the same number of 
points).
You must write a class (name it Question.py) to hold the data for a trivia 
question.  The class should have the following attributes:

A trivia question
Possible answer 1
Possible answer 2
Possible answer 3
Possible answer 4
The number of the correct answer (1, 2, 3, or 4)
The Question class should have an appropriate __init__ method, accessors and 
mutators.

Your program should have a list or dictionary containing 10 Question objects, 
one for each trivia question. You are to make up your own trivia questions. 

Submit both files (zip the two files if possible).


Our final exam is a real world problem about efficiency in a warehouse.  
3. 
XYZ Corporation sells products online.  The company has a large warehouse in 
which it stores its inventory of products.  Orders are picked, packed and 
shipped from the warehouse.

XYZ Corporation has contracted with you to write a program that will minimize 
the number of steps that the staff in the warehouse (called ODA's) take in 
picking the products ordered by customers.

The information you will need to complete this assignment are in the following 
files:

Specifications: CTIM285_Summer_2016_FinalExam.pdf
Warehouse Map: WarehouseImage.pdf
Data for Analysis:  warehouse_data_final_exam_Python.txt
Data for Analysis is saved in this order on each line of the file:
[orderNumber, partNumber, quantyNumber, aisleNumber, shelfNumber, binNumber]










Thanks,
Justin
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with error in paramiko

2016-07-24 Thread Alan Gauld via Tutor
On 23/07/16 09:12, José de Jesus Marquez Rangel wrote:
> Hello.
> 
> I have a problem because when I connect to the remote server via SSH gives
> me an error with paramiko library, but I connect to the same server with
> programs like putty, ssh and another there is no error.
> 
> Here the screenshot:
> 
> *Script.*
> [image: Imágenes integradas 1]
> 
> *the result of run*
> [image: Imágenes integradas 7]
> 

This is a text based forum and as such your images didn't make it
through the server. If possible just copy/paste the text into a mail
message.

Also paramiko is really outside the scope of this group (core language
and standard library) so you might do better on a paramiko forum
such as their mailing list:

 param...@librelist.com


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with error in paramiko

2016-07-24 Thread José de Jesus Marquez Rangel
Hello.

I have a problem because when I connect to the remote server via SSH gives
me an error with paramiko library, but I connect to the same server with
programs like putty, ssh and another there is no error.

Here the screenshot:

*Script.*
[image: Imágenes integradas 1]

*the result of run*
[image: Imágenes integradas 7]



*the result of log.*

The problem is when the ZAHO command with the library in the logs can see
the error highlighted runs.


*[image: Imágenes integradas 6]*

*PD: *The feature of the remote server unknown but the script work on the
Linux server.


Feature the computer client.

Windows 7 64bits.
Python3.4
Library paramiko,
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me out please

2016-07-20 Thread Danny Yoo
On Tue, Jul 19, 2016 at 4:31 AM, Marc Sànchez Quibus
 wrote:
> Hi,
> First of all I'm gonan introduce myself. My name is Marc and I'm a student
> and also a python's programmer begginer. I've been studying/learning python
> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or not.
> Is there some way to do it?

Hi Marc,

Yes.  You might want to read something like this to get some
background.  Phil Greenspun's Guide to Web Publishing:

http://philip.greenspun.com/panda/

Specifically, the chapter "Sites that are really progarms".

http://philip.greenspun.com/panda/server-programming

You mentioned that you have two scripts, one in Python and the other in HTML.

A web site can be seen as this: something that (1) takes in a web
request sent by a browser, and (2) spits out a web response.

A static web site takes in a web request, looks for an appropriate
file, and prints that file back as a web response.  But that's not the
only way we can build web responses.  A programmatic web site can take
that request and *generate* a web page on the fly.  A web site can
actually be a program: not just a plain text file.


There are a lot of resources to teach how to write programs that serve
web sites.  Another by the same author is
http://philip.greenspun.com/seia/, which goes into a lot more detail.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me out please

2016-07-19 Thread Bob Gailer
On Jul 19, 2016 9:24 AM, "Marc Sànchez Quibus" 
wrote:
>
> Hi,
> First of all I'm gonan introduce myself. My name is Marc and I'm a student
> and also a python's programmer begginer. I've been studying/learning
python
> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or
not.
> Is there some way to do it?

There might be. Tell us more about your situation.

> Thanks in advance and sorry for the inconvenience.

Since we are here to help, the only inconvenience his when we don't get
enough information. That seems to be typical for first time questioners.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me out please

2016-07-19 Thread Alan Gauld via Tutor
On 19/07/16 12:31, Marc Sànchez Quibus wrote:

> and now I need some help to finish my project.
> I have two scripts, one of them in python (the main script) and the other
> one written in html. Well, is just a brief javascript (an app) that I took
> by Github. I need to change a variable inside this html script. I was
> wondering wether I could change this variable from my python script or not.
> Is there some way to do it?

The easiest way is to put the entire html code into a string
inside a module:

# file: myhtml.py

html = """
Hello %s
"""

Then import that and use string formatting to insert the variable

#file: myscript.py
import myhtml
myvar = "World"
print myhtml.html % myvar

Instead of printing you could overwrite the original html file.

Or you could write a web based app using a framework like Flask
or Pylons and call your myscript.py from a web url and get it
to just serve the html string directly.

We don't know enough about your system and how the two
scripts are related to say more than that. But it might
give you some ideas.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help me out please

2016-07-19 Thread Marc Sànchez Quibus
Hi,
First of all I'm gonan introduce myself. My name is Marc and I'm a student
and also a python's programmer begginer. I've been studying/learning python
and now I need some help to finish my project.
I have two scripts, one of them in python (the main script) and the other
one written in html. Well, is just a brief javascript (an app) that I took
by Github. I need to change a variable inside this html script. I was
wondering wether I could change this variable from my python script or not.
Is there some way to do it?
Thanks in advance and sorry for the inconvenience.

-- 
*Marc Sànchez Quibus*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Alan Gauld via Tutor
On 06/07/16 15:04, loh...@tuta.io wrote:

> script, filename = argv
> txt = open (filename)
> 
> print "Here's your file %r: " % filename
> print txt.read()
> 
> print "Type the filename again: "
> file_again = raw_input("> ")
> 
> txt_again = open(file_again)
> print txt_again.read()


> why do I have to create a variable txt_again to assign it to the open 
> function and them print the file?

You don't, and could get away with a single
variable - filename. Like this:

filename = argv[1]
print "Here's your file %r: " % filename
print open(filename).read()

filename = raw_input("Type the filename again: >")
print open(filename).read()

But your book is (I assume) trying to teach you
good practice.

While you could have just printed the result of read directly,
its better not to over complicate code by doing too much in one
line (for a start, its harder to debug) the same variable.
Variables are cheap to create and if given useful names
tell us a lot about the purpose of the code.

In this case it's all a bit trivial, just printing the file
content, but if you were doing more complex processing
storing the file (and data) in variables would be the
best choice.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Michael Selik
On Wed, Jul 6, 2016 at 10:59 AM  wrote:

> why do I have to create a variable txt_again to assign it to the open
> function and them print the file?
> why is it that I can't only write something like open(file_again).read()?
>

Good insight. In fact you don't need to create the variable. The code ``data
= open('filename').read()`` will open the file named "filename" in the
current working directory, read it, and assign the data to a variable.

However, many programmers use variables not because they must, but because
good variable names can make code easier to read. Also, doing less stuff on
a line of code can make that code easier to read.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread lohecn
first, sorry everyone for having attached the file instead of just typing it 
here.
second, thanks a lot for the replies; even though I gave you no code it was 
quite helpful!
the code was this:

from sys import argv

script, filename = argv
txt = open (filename)

print "Here's your file %r: " % filename
print txt.read()

print "Type the filename again: "
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()

Peter Otten explained it to me line by line [thanks so much :)] however, I do 
have one more question:
why do I have to create a variable txt_again to assign it to the open 
function and them print the file?
why is it that I can't only write something like open(file_again).read()?


6. Jul 2016 05:22 by __pete...@web.de:


> loh...@tuta.io>  wrote:
>
>> hey everyone. this is my first time trying this -- actually, I've been
>> studying python only for some days now, and I'm afraid my questions are
>> going to be rally simple, but I can't seem to understand this piece of
>> code and thus can't move on.
>
> You seem to be talking about
>
> http://learnpythonthehardway.org/book/ex15.html
>
> """
> from sys import argv
>
> script, filename = argv
>
> txt = open(filename)
>
> print "Here's your file %r:" % filename
> print txt.read()
>
> print "Type the filename again:"
> file_again = raw_input("> ")
>
> txt_again = open(file_again)
>
> print txt_again.read()
> """
>
> As others said, always provide the code you are asking about, or if that is
> not possible at least provide a link.
>
>> you probably know the book, so you know that zed always makes us write
>> code so that then we can understand how it works, and it's great, but in
>> this exercise there are just too many new functions and without
>> explanation they are a bit hard to understand... so I'm having trouble
>> with most of the lines here.
>>
>> it's not that I want the full explanation to that code, but since I'm
>> unfamiliar with some of its concepts, I'm just going to tell you all the
>> things that I don't understand (sorry for it being a lot):
>> 1. the need to put script into an estipulation for argv (line 3)
>
> Write a script tmp.py containing
>
> from sys import argv
> print argv
>
> then call it with with one parameter, e. g.
>
> $ python tmp.py somefile.txt
> ['tmp.py', 'somefile.txt']
>
> As you can see argv is a list with two items, the first being "tmp.py", the
> name of the script you are invoking. You are only interested in the second
> one, the filename. The easy way to get that is
>
> filename = argv[1]
>
> the hard way is to use "unpacking"
>
> script, filename = argv
>
> where python will assign one item from the list on the right to every name
> on the left:
>
 items = ["foo", "bar"]
 one, two = items
 one
> 'foo'
 two
> 'bar'
>
> What happens if the number of names on the left doesn't match the number of
> items in the list?
>
 one, two, three = items
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: need more than 2 values to unpack
>
> You get an exception. That is why you have to provide the name "script" in
> Zed's example even though you are not actually interested in the script
> name.
>
>> 2. the what is txt and why it has to be used there (line 4)
>
> txt is a file object and
>
>> 3. txt.read() -- which are all new functions(? I dont even know what they
>> are)  (line 7)
>
> read() is a method that here reads the whole file into a string. You use 
> the
> open() function to open a file and usually assign the file object that is
> returned by open to a name. You can freely choose that name. The structure
> is the same for every object, be it a number:
>
> x = 42  # assign a number to x
> y = x + x  # do some arithmetic with x and assign the result to y
> print y  # print the result
>
> a list:
>
> mynumbers = list()  # create a list
> mynumbers.append(42)  # append a number to the list
> print mynumbers  # print the list
>
> or a file:
>
> myfile = open("example.txt")  # open the file example.txt in the current
>   # working directory. If the file doesn't 
> exist
>   # you get an error
>
> print "first line:", myfile.readline()  # read the first line and print it
> print "rest of the file:"
> print myfile.read()  # read the rest of the file and print it
>
> myfile.close()  # close the file
>
>> 4. file_again (line 10)
>> 5. txt_again (line 12)
>> and line 14.
>
> 4. and 5. are just a repetition of the first part, with the variation that
> the filename, assigned to file_again is read interactively with raw_input()
> instead of passing it as a commandline argument to the script.
>
> The names used can be freely chosen by the programmer, a script
>
> from sys import argv
>
> red_apple, my_hat = argv
>
> blue_suede_shoes = open(my_hat)
> print blue_suede_shoes.read()
> blue_suede_shoes.close()
>
> would work exactly like the first part of the hard-way example. However,
> picking descrip

Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Peter Otten
loh...@tuta.io wrote:

> hey everyone. this is my first time trying this -- actually, I've been
> studying python only for some days now, and I'm afraid my questions are
> going to be rally simple, but I can't seem to understand this piece of
> code and thus can't move on.

You seem to be talking about

http://learnpythonthehardway.org/book/ex15.html

"""
from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename
print txt.read()

print "Type the filename again:"
file_again = raw_input("> ")

txt_again = open(file_again)

print txt_again.read()
"""

As others said, always provide the code you are asking about, or if that is 
not possible at least provide a link.
 
> you probably know the book, so you know that zed always makes us write
> code so that then we can understand how it works, and it's great, but in
> this exercise there are just too many new functions and without
> explanation they are a bit hard to understand... so I'm having trouble
> with most of the lines here.
> 
> it's not that I want the full explanation to that code, but since I'm
> unfamiliar with some of its concepts, I'm just going to tell you all the
> things that I don't understand (sorry for it being a lot):
> 1. the need to put script into an estipulation for argv (line 3)

Write a script tmp.py containing

from sys import argv
print argv

then call it with with one parameter, e. g.

$ python tmp.py somefile.txt
['tmp.py', 'somefile.txt']

As you can see argv is a list with two items, the first being "tmp.py", the 
name of the script you are invoking. You are only interested in the second 
one, the filename. The easy way to get that is

filename = argv[1]

the hard way is to use "unpacking"

script, filename = argv

where python will assign one item from the list on the right to every name 
on the left:

>>> items = ["foo", "bar"]
>>> one, two = items
>>> one
'foo'
>>> two
'bar'

What happens if the number of names on the left doesn't match the number of 
items in the list?

>>> one, two, three = items
Traceback (most recent call last):
  File "", line 1, in 
ValueError: need more than 2 values to unpack

You get an exception. That is why you have to provide the name "script" in 
Zed's example even though you are not actually interested in the script 
name.

> 2. the what is txt and why it has to be used there (line 4)

txt is a file object and

> 3. txt.read() -- which are all new functions(? I dont even know what they
> are)  (line 7)

read() is a method that here reads the whole file into a string. You use the 
open() function to open a file and usually assign the file object that is 
returned by open to a name. You can freely choose that name. The structure 
is the same for every object, be it a number:

x = 42  # assign a number to x
y = x + x  # do some arithmetic with x and assign the result to y
print y  # print the result

a list:

mynumbers = list()  # create a list
mynumbers.append(42)  # append a number to the list
print mynumbers  # print the list

or a file:

myfile = open("example.txt")  # open the file example.txt in the current
  # working directory. If the file doesn't exist
  # you get an error

print "first line:", myfile.readline()  # read the first line and print it
print "rest of the file:"
print myfile.read()  # read the rest of the file and print it

myfile.close()  # close the file

> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

4. and 5. are just a repetition of the first part, with the variation that 
the filename, assigned to file_again is read interactively with raw_input() 
instead of passing it as a commandline argument to the script.

The names used can be freely chosen by the programmer, a script

from sys import argv

red_apple, my_hat = argv

blue_suede_shoes = open(my_hat)
print blue_suede_shoes.read()
blue_suede_shoes.close()

would work exactly like the first part of the hard-way example. However, 
picking descriptive names and using them consistently makes it much easier 
for a human reader to understand what's going on.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Alan Gauld via Tutor
On 06/07/16 00:56, loh...@tuta.io wrote:
> hey everyone. this is my first time trying this 

Welcome, but...

> you probably know the book,

Sorry, I don't and I suspect I'm not alone.
It's probably a fine book, but we don't all know it.

>  so you know that zed always makes us write code 
> so that then we can understand how it works, 

Good man Zed :-)

> exercise there are just too many new functions and without explanation they 
> are a bit hard to understand... so I'm having trouble with most of the lines 
> here.

And here's the next problem.
This is a text based mailing list. As such the server often strips out
attachments as potential security risks. So we can't see the code (I'm
assuming you attached it?)

> 1. the need to put script into an estipulation for argv (line 3)
> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they 
> are)  (line 7)
> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

Without sight of the code its hard to know what's going on.
But I suspect some of these "functions" are actually variables
(or objects) and hopefully zed has already discussed those?

Can you repost but include your code inside the mail message.
Also try to post in plain text since HTML tends to get garbled
in transit.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-06 Thread Michael Selik
On Tue, Jul 5, 2016 at 8:24 PM  wrote:

> I'm having trouble with most of the lines here.
>

It looks like you tried to attach a file. This mailing list does not allow
attachments. Instead, could you paste the code into your email?


> things that I don't understand:
> 1. the need to put script into an estipulation for argv (line 3)
> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they
> are)  (line 7)
>

I'm guessing txt is a file object or a file-like object that supports the
.read method to read the entire contents of the file into a single string
object.


> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-05 Thread Steven D'Aprano
Hi Heloisa, and welcome.

Do you have a link to the code? Or better still, if it is short (say 
under fifty lines) can you copy it into an email and send it?

On Wed, Jul 06, 2016 at 12:56:19AM +0100, loh...@tuta.io wrote:

[...]
> 1. the need to put script into an estipulation for argv (line 3)

I'm sorry, I don't know what that word "estipulation" means. Do you mean 
"stipulation", as in:

That which is stipulated, or agreed upon; that which is
definitely arranged or contracted; an agreement


> 2. the what is txt and why it has to be used there (line 4)
> 3. txt.read() -- which are all new functions(? I dont even know what they 
> are)  (line 7)
> 4. file_again (line 10)
> 5. txt_again (line 12)
> and line 14.

The only thing I can guess without seeing the code is that MAYBE txt is 
an open file, and txt.read() reads the content of the file.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-05 Thread boB Stepp

Welcome!

On 07/05/2016 06:56 PM, loh...@tuta.io wrote:

hey everyone. this is my first time trying this -- actually, I've been
studying python only for some days now, and I'm afraid my questions are going
to be rally simple, but I can't seem to understand this piece of code and
thus can't move on.

you probably know the book, so you know that zed always makes us write code
so that then we can understand how it works, and it's great, but in this
exercise there are just too many new functions and without explanation they
are a bit hard to understand... so I'm having trouble with most of the lines
here.


While this book is fairly well known, not everyone has a copy at hand. 
I would suggest that you resend your email with the full exercise typed 
into its body (This list does not accept attachments BTW.), and then 
pose your questions.  This way you provide the necessary context *in* 
your email body, so that everyone can follow along.


Cheers!
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] help with exercise 15 of zed shaw's LPTHW

2016-07-05 Thread lohecn
hey everyone. this is my first time trying this -- actually, I've been 
studying python only for some days now, and I'm afraid my questions are going 
to be rally simple, but I can't seem to understand this piece of code and 
thus can't move on.

you probably know the book, so you know that zed always makes us write code 
so that then we can understand how it works, and it's great, but in this 
exercise there are just too many new functions and without explanation they 
are a bit hard to understand... so I'm having trouble with most of the lines 
here.

it's not that I want the full explanation to that code, but since I'm 
unfamiliar with some of its concepts, I'm just going to tell you all the 
things that I don't understand (sorry for it being a lot):
1. the need to put script into an estipulation for argv (line 3)
2. the what is txt and why it has to be used there (line 4)
3. txt.read() -- which are all new functions(? I dont even know what they 
are)  (line 7)
4. file_again (line 10)
5. txt_again (line 12)
and line 14.

as you can see, it's pretty much everything. sorry about that.
I'd really appreciate any help at all!
thanks a lot,

heloisa
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2016-06-28 Thread David Palao
2016-06-28 7:54 GMT+02:00 Aaron Johnson :
> I have a program that is telling my i need your digital snake, but i dont
> want a snake. Help
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

I think you have to decide. I see two options:
1) keep obeying your program. That sounds a bit hazardous to me.
Consider that the 3 laws of robotics apply to machines not to humans!
2) Ignore your program.
You ask for help. My suggestion is: take 2).

Best
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2016-06-28 Thread Alan Gauld via Tutor
On 28/06/16 06:54, Aaron Johnson wrote:
> I have a program that is telling my i need your digital snake, but i dont
> want a snake. Help

I'm not sure what you expect us to do based on the information
you've given.

Can you be more specific?
What OS are you running?
On what platform (phone, tablet,laptop, desktop?)
What program says you need a snake (I assume you mean python?)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help

2016-06-28 Thread Aaron Johnson
I have a program that is telling my i need your digital snake, but i dont
want a snake. Help
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with comparing list of tuples in python 2

2016-06-20 Thread Lulu J
Many thanks to those of you who responded to my question. I really
appreciate.

Just to answer some questions you guys raised.

1.The list only contains the key words that was matched as a result of a
search. So words in this list aren't necessarily next to each other. They
could be anywhere in the text and the words can appear multiple times
2. The list is already sorted by the position
3.The main goal is to count the number of matches but to count adjacent
words only once. ie. two words or more next to each other counts as one
match.

Again, thank you for your time.
L

On Mon, Jun 20, 2016 at 8:34 AM, Muhubo Yusuf  wrote:

>
>
> From: Alan Gauld via Tutor 
> Date: Fri, Jun 17, 2016 at 6:36 PM
> Subject: Re: [Tutor] help with comparing list of tuples in python 2
> To: tutor@python.org
>
>
> On 17/06/16 20:18, Lulu J wrote:
>
> > I have a list of dictionaries. Each dictionary has a word and its
> position
> > in the text  the positions are in the form of a tuple.
> > Here is an example:
> > [
> > {'position': (5, 4), 'term': u'happy',},
> >  {'position': (5, 5), 'term': u'something'}
> > ]
> >
> > for the potions, the first element is the paragraph number and the second
> > is the word number in that paragraph(sequence from 1...n)
> >
> > What I would like to is find which words are next to each other. Meaning,
> > they will be in the same paragraph and the difference of their word
> numbers
> > is 1.
>
> You can sort them by providing a key function, for example,
> a simplified version::
>
> >>> L = [{'k':1,'v':0},{'k':5,'v':9},{'k':2,'v':6},{'k':0,'v':12}]
> >>> sorted(L,key=lambda d: d['v'])
> [{'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}, {'k': 0, 'v': 12}]
> >>> sorted(L,key=lambda d: d['k'])
> [{'k': 0, 'v': 12}, {'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}]
> >>>
>
> Then filter your results to find an adjacent pair that have matching
> positions. (This may not be necessary if you have all of the words since
> they should naturally be placed adjacent to each other, but
> if you only have key words it will be needed)
>
> Something like (untested)
>
> neighbours = [item for index,item in enumerate(data)
>   if item['position'][0] == data[index+1][position'][0] and
>   item['position'][1] == data[index+1][position'][1]-1]
>
> But there are lots of possible gotchas here.
>
> - look out for the last item which will give you an index error!
> - what happens to words that appear more than once? Are they
>   in your list more than once?
> - probably more :-(
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with comparing list of tuples in python 2

2016-06-18 Thread Peter Otten
Lulu J wrote:

> Hi there,
> 
> My apologies if this is a trivial question but I am sort of new to python.
> Here is my problem:
> I have a list of dictionaries. Each dictionary has a word and its position
> in the text  the positions are in the form of a tuple.
> Here is an example:
> [
> {'position': (5, 4), 'term': u'happy',},
>  {'position': (5, 5), 'term': u'something'}
> ]

How did you get your data? Perhaps it is possible to store it in a different 
data structure in the first place, one that is a better fit for your 
problem.

> for the potions, the first element is the paragraph number and the second
> is the word number in that paragraph(sequence from 1...n)
> 
> What I would like to is find which words are next to each other. Meaning,
> they will be in the same paragraph and the difference of their word
> numbers is 1.

What is the actual question your script has to answer? Is it

(1) What word precedes/follows the third word in the sixth paragraph?

or

(2) What words precede/follow the word u"happy"?

or something else I didn't think of?

For (2) here is a not-so-short self-contained example:

$ cat neighbors.py
import pprint
import sys

try:
raw_input
except NameError:
raw_input = input  # Python 3

SAMPLE = u"""\
The sky is blue
Press the blue button
This is pie in the sky
"""


def gen_terms(paragraphs):
"""Generate {"position": (para_index, word_index), "term": word} dicts.

A minimalistic emulation of what your code does.
"""
for para_index, para in enumerate(paragraphs):
for word_index, word in enumerate(para.lower().split()):
yield {"position": (para_index, word_index), "term": word}


def find_neighbors(word, position_to_word, word_to_position):
before = set()  # use collections.Counter() if you are
after = set()   # interested in frequencies
for para_index, word_index in word_to_position[word]:
try:
left_word = position_to_word[para_index, word_index-1]
except KeyError:
pass  # first word in paragraph
else:
before.add(left_word)
try:
right_word = position_to_word[para_index, word_index+1]
except KeyError:
pass  # last word in paragraph
else:
after.add(right_word)
return before, after


def format_words(words):
return ", ".join(sorted(words)) or ""


def build_lookup_tables(terms):
# map word to all positions in the text
word_to_position = {}
# map position to the corresponding word
position_to_word = {}
for term in terms:
pos = term["position"]
word = term["term"]
word_to_position.setdefault(word, []).append(pos)
position_to_word[pos] = word
return word_to_position, position_to_word


def normalize(word):
try:
word = word.decode()
except AttributeError:
pass  # Python 3
return word.lower()


def main():
verbose = "--verbose" in sys.argv
if verbose:
print("Original text:")
print(SAMPLE)

terms = list(gen_terms(SAMPLE.lower().splitlines()))
if verbose:
print("list of terms:")
pprint.pprint(terms)
print("")

word_to_position, position_to_word = build_lookup_tables(terms)
if verbose:
print("word --> position")
pprint.pprint(dict(word_to_position))
print("position --> word")
pprint.pprint(position_to_word)
print("")

while True:
word = normalize(raw_input("enter a word: "))
if not word:
print("Bye!")
break
elif word not in word_to_position:
print("Unknown word, enter one of these:")
print(format_words(word_to_position))
print("")
else:
before, after = find_neighbors(
word,
position_to_word=position_to_word,
word_to_position=word_to_position
)
print(u"These words occur before '{}'".format(word))
print(format_words(before))
print(u"These words occur after '{}'".format(word))
print(format_words(after))
print("")


if __name__ == "__main__":
main()

Let's run it in verbose mode so that you can see the data structures used:

$ python neighbors.py --verbose
Original text:
The sky is blue
Press the blue button
This is pie in the sky

list of terms:
[{'position': (0, 0), 'term': u'the'},
 {'position': (0, 1), 'term': u'sky'},
 {'position': (0, 2), 'term': u'is'},
 {'position': (0, 3), 'term': u'blue'},
 {'position': (1, 0), 'term': u'press'},
 {'position': (1, 1), 'term': u'the'},
 {'position': (1, 2), 'term': u'blue'},
 {'position': (1, 3), 'term': u'button'},
 {'position': (2, 0), 'term': u'this'},
 {'position': (2, 1), 'term': u'is'},
 {'position': (2, 2), 'term': u'pie'},
 {'position': (2, 3), 'term': u'in'},
 {'position': (2, 4), 'term': u'the'},
 {'position': (2, 5), 'term': u'sky'}]

word --> posit

Re: [Tutor] help with comparing list of tuples in python 2

2016-06-18 Thread Michael Selik
On Fri, Jun 17, 2016, 6:12 PM Lulu J  wrote:

> Hi there,
>
> My apologies if this is a trivial question but I am sort of new to python.
> Here is my problem:
> I have a list of dictionaries. Each dictionary has a word and its position
> in the text  the positions are in the form of a tuple.
> Here is an example:
> [
> {'position': (5, 4), 'term': u'happy',},
>  {'position': (5, 5), 'term': u'something'}
> ]
>
> for the potions, the first element is the paragraph number and the second
> is the word number in that paragraph(sequence from 1...n)
>
> What I would like to is find which words are next to each other. Meaning,
> they will be in the same paragraph and the difference of their word numbers
> is 1.
>

Put the words in a dictionary, key is the location, value is the word.

Sort the location-word pairs by location. Loop over the result pairwise.

>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with comparing list of tuples in python 2

2016-06-17 Thread Alan Gauld via Tutor
On 17/06/16 20:18, Lulu J wrote:

> I have a list of dictionaries. Each dictionary has a word and its position
> in the text  the positions are in the form of a tuple.
> Here is an example:
> [
> {'position': (5, 4), 'term': u'happy',},
>  {'position': (5, 5), 'term': u'something'}
> ]
> 
> for the potions, the first element is the paragraph number and the second
> is the word number in that paragraph(sequence from 1...n)
> 
> What I would like to is find which words are next to each other. Meaning,
> they will be in the same paragraph and the difference of their word numbers
> is 1.

You can sort them by providing a key function, for example,
a simplified version::

>>> L = [{'k':1,'v':0},{'k':5,'v':9},{'k':2,'v':6},{'k':0,'v':12}]
>>> sorted(L,key=lambda d: d['v'])
[{'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}, {'k': 0, 'v': 12}]
>>> sorted(L,key=lambda d: d['k'])
[{'k': 0, 'v': 12}, {'k': 1, 'v': 0}, {'k': 2, 'v': 6}, {'k': 5, 'v': 9}]
>>>

Then filter your results to find an adjacent pair that have matching
positions. (This may not be necessary if you have all of the words since
they should naturally be placed adjacent to each other, but
if you only have key words it will be needed)

Something like (untested)

neighbours = [item for index,item in enumerate(data)
  if item['position'][0] == data[index+1][position'][0] and
  item['position'][1] == data[index+1][position'][1]-1]

But there are lots of possible gotchas here.

- look out for the last item which will give you an index error!
- what happens to words that appear more than once? Are they
  in your list more than once?
- probably more :-(


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] help with comparing list of tuples in python 2

2016-06-17 Thread Lulu J
Hi there,

My apologies if this is a trivial question but I am sort of new to python.
Here is my problem:
I have a list of dictionaries. Each dictionary has a word and its position
in the text  the positions are in the form of a tuple.
Here is an example:
[
{'position': (5, 4), 'term': u'happy',},
 {'position': (5, 5), 'term': u'something'}
]

for the potions, the first element is the paragraph number and the second
is the word number in that paragraph(sequence from 1...n)

What I would like to is find which words are next to each other. Meaning,
they will be in the same paragraph and the difference of their word numbers
is 1.

Any help would be appreciated.

Thank you
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with 'if' statement and the concept of None

2016-05-31 Thread Ben Finney
marat murad via Tutor  writes:

> The author introduced a new way of coding the Boolean NOT operator
> with the 'if' statement I have highlighted the relevant
> area,apparently this if statement actually means if money != 0,which I
> understood

Not quite. The statement actually means “if ‘money’ evaluates as true”.

Any Python value can be interrogated with the question “Are you true or
false?”, and that is what the ‘if’ statement does.

This is different from asking ”Is this the True constant or the False
constant?” because for most values the answer is ”Neither”.

In Python the question “Is this value true, or false?” is usually
implemented as ”Is this value something, or nothing?”. If the value is
conceptually nothing, it evaluates as false when interrogated in a
boolean context.

See the Python documentation for a comprehensive list of false values
https://docs.python.org/3/library/stdtypes.html#truth-value-testing>;
any not-false value is true by default.

If you learn the conceptual “if it's not something, it's false”, then
you will have a fairly good intuition for how ‘if somevalue’ works.

-- 
 \“None can love freedom heartily, but good men; the rest love |
  `\   not freedom, but license.” —John Milton |
_o__)  |
Ben Finney

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with 'if' statement and the concept of None

2016-05-31 Thread Steven D'Aprano
On Tue, May 31, 2016 at 04:16:21PM +0100, marat murad via Tutor wrote:

> money = int(input("How many dollars do you slip the Maitr D'? "))
> *if money:*
> print("Ah I think I can make something work")
> else:
> print("Please sit ,it may be a while")

All values in Python can be used where a true or false boolean value is 
expected, such as in an "if" or a "while" statement. We call this a 
"boolean context", meaning something which expects a true or false flag.

So we have True and False (with the initial capital letter) as special 
constants, but we also can treat every other value as if they were true 
or false (without the initial capital). Sometimes we call them "truthy" 
and "falsey", or "true-like" and "false-like" values.

For Python built-ins, we have:

Falsey (false-like) values:

- zero: 0, 0.0, 0j, Fraction(0), etc.
- empty strings: "", b""
- empty containers: [], (), {}, set() etc.
  (empty list, empty tuple, empty dict, empty set)
- sequences with len() == 0
- None
- False

Truthy (true-like) values:

- non-zero numbers: 1, 2.0, 3j, Fraction(4, 5), etc.
- non-empty strings: "Hello world!", b"\x0"
  (yes, even the null-byte is non-empty, since it has length 1)
- non-empty containers
- sequences with len() != 0
- classes, object()
- True

We say that "false values represent nothing", like zero, empty strings, 
None, and empty containers; while "true values represent something", 
that is, anything which is not nothing.


So any time you have a value, say, x, we can test to see if x is a 
truthy or falsey value:


values = [1, 5, 0, -2.0, 3.7, None, object(), (1, 2), [], True]
for x in values:
if x:
print(x, "is a truthy value")
else:
print(x, "is a falsey value")




-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with 'if' statement and the concept of None

2016-05-31 Thread Alan Gauld via Tutor
On 31/05/16 16:16, marat murad via Tutor wrote:

> program  whose code I have pasted below. The author introduced a new way of
> coding the Boolean NOT operator with the 'if' statement I have highlighted
> the relevant area,apparently this if statement actually means if money !=
> 0,which I understood,

Boolean values are either true or false.
Other values are given boolean equivalent values by Python.
eg. For strings an empty string is False, anything else is True.
For numbers 0 is False anything else is True.

So in your example:

> *if money:*
> print("Ah I think I can make something work")
> else:
> print("Please sit ,it may be a while")
>

The first 'if' test is saying

'if money is equivalent to True' (anything other than zero)

In effect that's the same as you said (it's like testing for != 0)
but the important difference is that it is relying
on the boolean *equivalence* of an integer value.
The same is true in your second example:

> idea of slicing also has a if statement similar to the first one,except the
> second one accepts  0 value but the first one doesn't.
> 

> start=input("\nStart: ")
> 
>* if start:*
> start=int(start)

Again this is really saying if start is True and for a string
(which is what input() returns), as I said above, True means
not empty. So the string '0' is not empty and therefore True.
It's not the value of the character that matters it's the fact
that there is a character there at all.

All objects in Python have these boolean equivalent values,
for example an empty list, tuple,set or dictionary is also
considered False. As is the special value None.

> I hope i made sense.

Yes, although your subject also mentions the concept of None?
Did you have another question about that?

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with 'if' statement and the concept of None

2016-05-31 Thread marat murad via Tutor
Hi
I'm learning how to code with python an I have purchased the book 'Python
Programming for the absolute beginner,third edition' by Michael Dawson.
There is one concept that is confusing me in chapter 3 page 71 there is a
program  whose code I have pasted below. The author introduced a new way of
coding the Boolean NOT operator with the 'if' statement I have highlighted
the relevant area,apparently this if statement actually means if money !=
0,which I understood,but the program below this one which introduces the
idea of slicing also has a if statement similar to the first one,except the
second one accepts  0 value but the first one doesn't.

print("Welcome to the Chateau D'food")
print("It seems we are quit full today.\n")

money = int(input("How many dollars do you slip the Maitr D'? "))

*if money:*
print("Ah I think I can make something work")
else:
print("Please sit ,it may be a while")


input("\nPress enter to exit")


The slicing program

word = "existential"

print("Enter the beginning and ending index for the word existential")
print("press he enter key at 'Start' to exit")

start= None
while start != "":
start=input("\nStart: ")

   * if start:*
start=int(start)

finish=int(input("Finish: "))

print ("word[",start, ":",finish, "]is " , end="")
print(word[start:finish])

input("\nPress enter to exit")

I hope i made sense.

Thankyou
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with python

2016-04-19 Thread Alan Gauld
On 19/04/16 10:13, Tim Golden wrote:

> In any recent version of Windows (ie Vista & later) the most common way 
> to find a program is to press the "Start" button or the "Windows" key 
> and just start typing its name

Interesting, I've been using Windows 10 since it came out and didn't
know about that trick. I also haven't noticed it any of the PC mags I've
read recently.

> The same for the getting a command prompt up: press "Start/Windows" and 
> type "Command". 

I usually hit Windows->R and type cmd.
So that's less useful for me.

But thanks for the tip.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with python

2016-04-19 Thread Tim Golden

On 19/04/2016 10:03, Alan Gauld wrote:

However, for now, you probably want to use IDLE which should
come with Python. (It is sometimes called Python GUI on
Windows too.)

You should find it under Python in your All Programs view.


In any recent version of Windows (ie Vista & later) the most common way 
to find a program is to press the "Start" button or the "Windows" key 
and just start typing its name -- ie rather than actually navigating 
through a cascade of menus. (I think on other systems this is called a 
"Finder" or "Launcher" or something).


In this particular case, pressing "Start/Windows" and typing "IDLE" 
gives -- in my case -- several options, including 3.4 64-bit etc. 
Hopefully, for the OP, there will be just one.


The same for the getting a command prompt up: press "Start/Windows" and 
type "Command". Obviously it will depend on what's installed but for me 
the "Command Prompt" icon is the top of the resulting search list.


Hope that helps people who are not used to (recent) Windows and are 
trying to advise novice users.


TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with python

2016-04-19 Thread Alan Gauld
On 19/04/16 02:20, Bereke via Tutor wrote:
> Hello there:
> 
>   i am facing some problem with my python programming language which is 
> already installed in My laptop lenovo, 8.1 OS.

I'm assuming that means Windows 8.1?

> The existing language says "python 27 ". when i click on it, 
> it turns to "python or pythonw".

I don't know what you mean when you say "click on it".
Where are you clicking? The desktop? A menu? Windows explorer?
And where does it say python or pythonw?

> I can write on its dark surface, but it does not have tools like file, play, 
> edit,...

It sounds like you are opening the Python interpreter in
a command console. It will be helpful for you to learn how
to use that console. There are several tutorials on the web
if you search for "Windows command line".

However, for now, you probably want to use IDLE which should
come with Python. (It is sometimes called Python GUI on
Windows too.)

You should find it under Python in your All Programs view.

Alternatively you can use Windows Explorer to search for
the idle.bat file. Once you find it you can create a
shortcut to your desktop or your start menu.
3
> what i need is, to be able to program on it, 

You can program using notepad and the console that you have
but IDLE will be a better experience.

On my Windows 10 box IDLE lives in this folder:

C:\Python34\Lib\idlelib

It should be similar for Windows 8.1

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with python

2016-04-19 Thread Bereke via Tutor
Hello there:

  i am facing some problem with my python programming language which is already 
installed in My laptop lenovo, 8.1 OS. The existing language says "python 27 ". 
when i click on it, it turns to "python or pythonw". I can write on its dark 
surface, but it does not have tools like file, play, edit,...on the tool box. 
And i can not Copy past from it.
  when i down load a new 2.7.11 or 3.51 or any other version, it dawnloads only 
text, but what i need is, to be able to program on it, i.e to write on it and 
copy- paste my assignments.
  Could you give me some help please?

Best regards

Bere


Sent from Samsung Mobile
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with recursion

2016-03-22 Thread Martin A. Brown

Greetings and welcome Lucas (Beterraba),

>Hello, I'm new to both Python and such a mailling list.
>I'm not sure how it works (if it does).

First, welcome to Python!  We hope you like Python and are happy to 
help you figure out how to get started.

The mailing list etiquette is like most mailing lists (be polite, 
be clear, do not top post).  This is an English language mailing 
list.

In addition on this mailing list, we ask people to:

  * report operating system and Python version they are using
  * copy/paste the code under question (and/or any errors)
  * include a question (like for example "I expected X to happen, 
but Y happened instead.  Why?")

>I would really appreciate if anyone could help me with a small piece of
>code I'm implementing in order to learn some recursion.

Recursion is a wonderful technique.  One of the classic computer 
science examples demonstrating recursion (and the limits of 
recursion) is a function implementing the Fibonacci sequence.

  https://technobeans.wordpress.com/2012/04/16/5-ways-of-fibonacci-in-python/

But, if you have a more specific question about recursion, then 
please send it along.

Welcome to the world of Python!

-Martin

-- 
Martin A. Brown
http://linux-ip.net/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with recursion

2016-03-22 Thread Joel Goldstick
On Tue, Mar 22, 2016 at 8:27 AM, Steven D'Aprano 
wrote:

> On Tue, Mar 22, 2016 at 09:12:18AM +, Lucas Cavalcante wrote:
> > Hello, I'm new to both Python and such a mailling list.
> > I'm not sure how it works (if it does).
> > I would really appreciate if anyone could help me with a small piece of
> > code I'm implementing in order to learn some recursion.
>
> Sure. Show us your code and ask your question.
>
>
>
> --
> Steve
>

..or ... google python recursion -- lots of tutorials.  If you get stuck,
as Steven posted, show some code, and ask a question

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/ 
http://cc-baseballstats.info/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with recursion

2016-03-22 Thread Steven D'Aprano
On Tue, Mar 22, 2016 at 09:12:18AM +, Lucas Cavalcante wrote:
> Hello, I'm new to both Python and such a mailling list.
> I'm not sure how it works (if it does).
> I would really appreciate if anyone could help me with a small piece of
> code I'm implementing in order to learn some recursion.

Sure. Show us your code and ask your question.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with recursion

2016-03-22 Thread Lucas Cavalcante
Hello, I'm new to both Python and such a mailling list.
I'm not sure how it works (if it does).
I would really appreciate if anyone could help me with a small piece of
code I'm implementing in order to learn some recursion.
Cheers,
Beterraba
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with an error

2016-03-05 Thread Alan Gauld
On 05/03/16 19:36, Saad Mabror wrote:

> i've installed python 2.7 on my laptop (running windows 7 ) 

> i started receveing syntax error  dialogues on IDLE  even 
> if i'm writing just one simple line such as ( print "hello world") .

The most likely reason is that you have somehow installed Python v3 and
are trying to run code for v2 in v3.
What does the IDLE shell window say when it starts?

Look at the message that looks like:

Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>>

Is it v2.7 or 3.x?

If that's not the problem can you cut 'n paste a full transcript
of your code and the error message?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with an error

2016-03-05 Thread boB Stepp
On Sat, Mar 5, 2016 at 1:36 PM, Saad Mabror  wrote:
> Hello , So i'm totally new to programming and i decided to start with python 
> , i've installed python 2.7 on my laptop (running windows 7 ) at first i 
> started following a begginer's guide and everything was fine . But later i 
> started receveing syntax error  dialogues on IDLE  even if i'm writing just 
> one simple line such as ( print "hello world") . I already tried uninstalling 
> and reinstalling but that didn't work , so is there any possible way to fix 
> this ? Thanks in Advance .
> ___

It would be helpful if you would copy and paste into a plain text
email to this group exactly what you typed into IDLE and the full
trace back of the error message you receive.

On a side note, if you are just starting to learn Python and have no
special need for Python 2, then you should work on learning Python 3.

-- 
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with an error

2016-03-05 Thread Saad Mabror
Hello , So i'm totally new to programming and i decided to start with python , 
i've installed python 2.7 on my laptop (running windows 7 ) at first i started 
following a begginer's guide and everything was fine . But later i started 
receveing syntax error  dialogues on IDLE  even if i'm writing just one simple 
line such as ( print "hello world") . I already tried uninstalling and 
reinstalling but that didn't work , so is there any possible way to fix this ? 
Thanks in Advance . 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with Python code

2016-02-29 Thread Alan Gauld
On 29/02/16 17:31, Donald Woolfolk wrote:
> Hello, 
> 
> I am new to Python 3.5 and I am writing code to get data 
> from a session api call and load that data into a csv file
> or a MySQL database.

That's great, we can help with that, but...

> I am able to make the session call and also to connect to 
> the MySQL db, but I am not able to convert the result (JSON) data.

We can't read minds. You need to show us your code.
Show us your input and output data. Tell us where you are stuck.
Include full error messages where appropriate. Tell us your
OS and Python version too.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with Python code

2016-02-29 Thread Donald Woolfolk
Hello, 

I am new to Python 3.5 and I am writing code to get data from a session api 
call and load that data into a csv file or a MySQL database. I am able to make 
the session call and also to connect to the MySQL db, but I am not able to 
convert the result (JSON) data. I would like assistance with this if possible.

Thanks,
Don
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with date range

2016-02-09 Thread Alan Gauld
On 09/02/16 15:34, Chelsea G wrote:

> Then in the csv file I want to search for a certain range of dates like
> 1/3/2016 - 2/3/2016. I can get individual dates but not a range of dates. 

Can ytou simplify the problem momentaruily?
Can you create a list of dates then search that list for a
range of dates? That is forget about the csv file issues
and focus on the date problem? That might make it easier
to see where you are having the issues.

> have an if elif statement to read row5 which is the date row. My if
> statement is the initial pass at returning the values within the date range
> and then my elif is the parameter and if there is no parameter passed in
> then it returns all data. I am having some trouble trying to pass in a date
> range parameter. 

How are you trying to represent the date range? As two dates?
Or as date and a timedelta object? Or some thing else?(what?)

> def populate_dict(self, filename, date_choice, key_choice):

Unfortunately in Python we can't tell much about the types
of your parameters from the declaration.


> with open(filename, 'rb') as f:
> reader = csv.reader(f)
> next(reader, None) #
> for row in reader:
>   if date_choice == row[5]:
>   self.dict[row[2]].append(row[3])

row[5] will be a string so this suggests your date_choice is
a string representation of a single date? That obviously cannot
be a range you need a start and end point. And then you need
to see if the target date lies between those two points. And
for that you need a way to compare them. Comparing dates as
a general problem is very, very difficult.

Fortunately the datetime module and the timedelta object
within it simplifies things for your use case.



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with date range

2016-02-09 Thread Martin A. Brown

Greetings Chelsea,

>So what I am trying to do is take in a csv file and the format of 
>the csv file is:

While I do not have a suggestion to you about the Python you have 
sent to the list, I have a few suggestions about how to approach the 
problem differently.  I hope that this may make your task easier.

>something, something1, something2,something3, something4, 
>something5, something6, something7. Then in the csv file I want to 
>search for a certain range of dates like 1/3/2016 - 2/3/2016. I can 
>get individual dates but not a range of dates.


Option 1 for date handling:

Consider converting your date column to a datetime object, which 
then can be used in comparisons (and sorting).

  >>> d0 = datetime.datetime.strptime('1/3/2016', '%m/%d/%Y')
  >>> d1 = datetime.datetime.strptime('2/3/2016', '%m/%d/%Y')
  >>> d0 > d1
  False
  >>> d0 < d1
  True

This is good for general date and time handling.  If you are only 
handling date,s then you may wish to use the strptime() function to 
parse your date and then choose to convert it to a date.  See also 
below my point about serialized (on disk) representation and memory 
representation.


Option 2 for date handling:

Consider converting your date to a time struct, which can then by 
used in comparisons and sorting.

  >>> t0 = time.strptime('1/3/2016', '%m/%d/%Y')
  >>> t1 = time.strptime('2/3/2016', '%m/%d/%Y')
  >>> t0 > t1
  False
  >>> t0 < t1
  True

The time library is good, too.  I like it because I have, 
historically, preferred the Epoch timestamp, which is how several 
classes of computers expose their time-tracking to applications.

  >>> time.time()
  1455044423.592147


>I have an if elif statement to read row5 which is the date row. My 
>if statement is the initial pass at returning the values within the 
>date range and then my elif is the parameter and if there is no 
>parameter passed in then it returns all data.

>I am having some trouble trying to pass in a date range parameter. 
>The piece of code is under the def populate_dict function the 
>date_choice part. Here is the code:

Even though I would separate the selection of record from the 
reading and conversion of the data (see more below), I think you 
want to do something more like this (to handle a range of time):

def populate_dict(self, filename, date_choice, key_choice):
# -- date_choice must be a list/tuple of datetime types (datetime, 
datetime)
with open(filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None) # -- skipping the header, eh?
for row in reader:
eventdate = datetime.datetime.strptime(row[5], '%m/%d/%Y')

if date_choice is None:
   self.dict[row[2]].append(row[3])
elif date_choice[0] <= eventdate <= date_choice[1]:
   self.dict[row[2]].append(row[3])

if key_choice == row[3]:
   self.dict[row[2]].append(row[3])
elif key_choice == "none":
   self.dict[row[2]].append(row[3])

Handling time ranges is always a wee bit tricky.  If you don't 
convert the data into some sort of convenient format before trying 
to apply the range criteria, you'll slowly go crazy trying to figure 
out what is wrong.

How much data do you have?  I'm assuming it is small(er than half a 
million rows).  If so, then, there's no harm in loading it all into 
memory and then filtering in (or out) the stuff you want.

But, most importantly, I have a general suggestion about separating 
the serialized (on-disk) format from the format you are using in 
memory.  I will make reference to another data handling library in 
Python, but mostly to illustrate the idea.

You can read CSV data sets with a tool called pandas [0].  There are 
many reasons it is popular, but I'll examine one feature.  If you 
load a CSV file using pandas, it tries to apply a bit of inference 
logic to each data type as it reads a file.  You said that the sixth 
column of your data is a date-formatted field.

If the pandas library can determine that the sixth field in every 
row can be converted to a datetime() type (or an int() or a float(), 
etc.), it will automatically convert that field.  This is useful 
because the serialized form is a string that looks like '1/3/2016' 
or '2016-02-09 11:13:06' or 'Tue Feb  9 19:13:24 UTC 2016'.

But, you as a human are not thinking "this is a string".  You are 
thinking of it as a date.  So, simply put:

  Serialized form:  a string representation that contains a date
  Form in memory:  a date, datetime, or time type (of some kind)

Again, if you are working with a small amount of data (like 
less than 50MB), don't be afraid to load it into memory.  You can 
make things more efficient later, if need be.  If you have a larger 
data set or you want to perform all sorts of different computations, 
sorting and grouping, you may find a SQLite database a good solution 
(as Joel Goldstick

Re: [Tutor] Help with date range

2016-02-09 Thread Joel Goldstick
On Tue, Feb 9, 2016 at 10:34 AM, Chelsea G  wrote:

> So what I am trying to do is take in a csv file and the format of the csv
> file is:
> something, something1, something2,something3, something4, something5,
> something6, something7.
> Then in the csv file I want to search for a certain range of dates like
> 1/3/2016 - 2/3/2016. I can get individual dates but not a range of dates. I
> have an if elif statement to read row5 which is the date row. My if
> statement is the initial pass at returning the values within the date range
> and then my elif is the parameter and if there is no parameter passed in
> then it returns all data. I am having some trouble trying to pass in a date
> range parameter. The piece of code is under the def populate_dict function
> the date_choice part. Here is the code:
>
> import csvimport jsonimport sysimport osfrom collections import
> defaultdictfrom collections import Counter
>
>
> The above imports are a mess! Can you format them correctly?


> UPPER_LIMIT = 5
> LOWER_LIMIT = 4
> class dictionary():
> def __init__(self):
> self.dict = defaultdict(list)
> self.counted_dict = defaultdict(list)
> self.grouped_dict = defaultdict(list)
> self.total_dict = defaultdict(list)
>
>
> def populate_dict(self, filename, date_choice, key_choice):
> with open(filename, 'rb') as f:
> reader = csv.reader(f)
> next(reader, None) #
> for row in reader:
> if date_choice == row[5]:
> self.dict[row[2]].append(row[3])
> elif date_choice == "none":
> self.dict[row[2]].append(row[3])
> if key_choice == row[3]:
> self.dict[row[2]].append(row[3])
> elif key_choice == "none":
> self.dict[row[2]].append(row[3])   def
> all_counts(self):
> data_count = Counter()
> for key in self.dict.keys():
> self.counted_dict.update({key: Counter(self.dict[key])})
> # returns the total counts for each application
> def total_counts(self):
> self.total_dict.update({'Application': 'Incident Count'})
> for key in self.dict.keys():
> total = 0
> b = Counter(self.dict[key])
> for value in b:
> total += b[value]
> self.total_dict.update({key: total})
> # returns the counts of incidents if they are greater than or equal to
> 5, and groups the rest in an "other" category
> def grouped_counts(self):
> for key in self.dict.keys():
> total = 0
> c = Counter(self.dict[key])
> self.grouped_dict[key].append(['Description', 'Incident
> Count'])
> for value in c:
> if c[value] >= UPPER_LIMIT:
> grouped_list = value, c[value]
> self.grouped_dict[key].append(grouped_list)
> elif c[value] <= LOWER_LIMIT:
> total += c[value]
> other_list = "other ", total
> self.grouped_dict[key].append(other_list)
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Its hard to tell what you want to do.  You should show a small (10 lines?)
input table, and show the results you want.

This is probably much easier to solve by importing csv to a sqlite
database, then running some simple date range queries.  Do you know any sql?

-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with date range

2016-02-09 Thread Chelsea G
So what I am trying to do is take in a csv file and the format of the csv
file is:
something, something1, something2,something3, something4, something5,
something6, something7.
Then in the csv file I want to search for a certain range of dates like
1/3/2016 - 2/3/2016. I can get individual dates but not a range of dates. I
have an if elif statement to read row5 which is the date row. My if
statement is the initial pass at returning the values within the date range
and then my elif is the parameter and if there is no parameter passed in
then it returns all data. I am having some trouble trying to pass in a date
range parameter. The piece of code is under the def populate_dict function
the date_choice part. Here is the code:

import csvimport jsonimport sysimport osfrom collections import
defaultdictfrom collections import Counter


UPPER_LIMIT = 5
LOWER_LIMIT = 4
class dictionary():
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.total_dict = defaultdict(list)


def populate_dict(self, filename, date_choice, key_choice):
with open(filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None) #
for row in reader:
if date_choice == row[5]:
self.dict[row[2]].append(row[3])
elif date_choice == "none":
self.dict[row[2]].append(row[3])
if key_choice == row[3]:
self.dict[row[2]].append(row[3])
elif key_choice == "none":
self.dict[row[2]].append(row[3])   def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})
# returns the total counts for each application
def total_counts(self):
self.total_dict.update({'Application': 'Incident Count'})
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: total})
# returns the counts of incidents if they are greater than or equal to
5, and groups the rest in an "other" category
def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
self.grouped_dict[key].append(['Description', 'Incident Count'])
for value in c:
if c[value] >= UPPER_LIMIT:
grouped_list = value, c[value]
self.grouped_dict[key].append(grouped_list)
elif c[value] <= LOWER_LIMIT:
total += c[value]
other_list = "other ", total
self.grouped_dict[key].append(other_list)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed

2016-02-04 Thread Alan Gauld
On 04/02/16 23:26, Tom Brodle wrote:

> While true:
> Turn LED on
> sleep 5 seconds
> Turn LED off
> sleep .5 seconds  

> # Coming from the world of Basic I did/do not understand what made the 
> program loop
> # back to while True: line of code.

Its the indentation
In BASIC you would write

WHILE TRUE
   TURN LED ON
   SLEEP 5s
   TURN LED OFF
   Sleep 0.5s
WEND

In Python the Wend is implicit in the indentation.

> # I  wanted the LED to turn on and then off and stay off, 

In that case you didn't want a while loop, you just
wanted a sequence:

Turn LED on
sleep 5 seconds
Turn LED off

> # page I became aware of quit(code=None) and inserted it 

That quits the entire program.
That's OK if that's what you want but if yyou need to do
something else after wards its not too helpful.

If you really want to break out of a 'while True' loop you
need to use the 'break' statement, usually inside some
kind of if statement

while True
if some condition:
   break   # exit the loop
do whatever the loop does


> GPIO.cleanup()   
> # I was told to put this line in but I do not know where it goes

Probably after the loop - that is without any indentation.
You are best to put it in a 'finally' clause like this

try:
   while True:
   loop code here
finally:  # always executed
   GPIO.cleanup()

Then even if you hit an error condition that forces an exit
from the loop the finally is guaranteed to be executed.

> #The code did turn the LED on once and then it did stay off, 
> but it gave me a message that the  program is still running.

> I did not think that programs actually did stop until the
> power was removed.

Probably not because the while never exits.
BTW the LED is not really staying on from the look of things.
Its turning on for 5 seconds then off for 0.5s. Its just that
the off is too short to notice.

For more about Python loops you can check out my tutorial below.
(While loops are coverd about half way down the loops topic)
If you know BASIC the examples are nearly all repeated in
VBScript (a form of BASIC) so you should recognise the patterns.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help needed

2016-02-04 Thread Joel Goldstick
On Thu, Feb 4, 2016 at 6:26 PM, Tom Brodle  wrote:

> I am very new  to Python.  I am just practicing code using a simple plug
> board.  The code is working as I want it to but the last message and the
> original looping makes me have questions.  Because the main code works I
> will just abbreviate it.
>
> import GPIO
> import time
> Gpio setmode (BCM)
> led_pin = 18
> GPIO setup(led_pin, GPIO)
>
> try:
> While true:
>

Actually you need:
While True:

This means run forever.  In the while loop you need some test to break or
this loop will run forever.  You can press Ctl-C to quit the program



> Turn LED on
> sleep 5 seconds
> Turn LED off
> sleep .5 seconds  # program was initially designed to keep LED
> turning on and off and that worked.
># Coming from the world of
> Basic I did/do not understand what made the program loop
># back to while True: line of
> code.
># I  wanted the LED to turn on
> and then off and stay off, so from some Python.org
># page I became aware of
> quit(code=None) and inserted it before the line Print("Cleaning up")
>   quit(code=None)# I put this line in to stop the
> looping back to While true:.
> Print("Cleaning up")
> GPIO.cleanup()   # I was told to put this line in but I do not
> know where it goes to do whatever.
>   #The code did turn the LED on
> once and then it did stay off, but it gave me a message that
>   # the  program is still
> running.  I did not think that programs actually did stop until the
>   # power was removed.
>
> Thanks
> Tom
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help needed

2016-02-04 Thread Tom Brodle
I am very new  to Python.  I am just practicing code using a simple plug board. 
 The code is working as I want it to but the last message and the original 
looping makes me have questions.  Because the main code works I will just 
abbreviate it.

import GPIO
import time
Gpio setmode (BCM)
led_pin = 18
GPIO setup(led_pin, GPIO)

try:
While true:
Turn LED on
sleep 5 seconds
Turn LED off
sleep .5 seconds  # program was initially designed to keep LED 
turning on and off and that worked.
   # Coming from the world of Basic I 
did/do not understand what made the program loop
   # back to while True: line of code.
   # I  wanted the LED to turn on and 
then off and stay off, so from some Python.org 
   # page I became aware of 
quit(code=None) and inserted it before the line Print("Cleaning up")
  quit(code=None)# I put this line in to stop the looping back 
to While true:.
Print("Cleaning up")
GPIO.cleanup()   # I was told to put this line in but I do not know 
where it goes to do whatever. 
  #The code did turn the LED on once 
and then it did stay off, but it gave me a message that 
  # the  program is still running.  I 
did not think that programs actually did stop until the
  # power was removed.

Thanks
Tom
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with error

2016-02-02 Thread Alan Gauld
On 02/02/16 15:37, Chelsea G wrote:

> 'issues' and output those results into a text file. I just need some help
> with figuring out how to fix the error I am receiving.

Joel has already pointed out the indentation error in your class.

However there is another problem... but possibly not with your code.

> And then I have another python file where I import my functions and
> run the results. Here is the code for that:
> 
> import functions2
> 
> week_choice = raw_input("Previous Week or Current Week?")if
> week_choice == "current week":
>   data = functions2.dictionary()
>   filename = raw_input("What file do you want to use?")
>   data.populate_dict(filename)
>   data.total_counts()
>   data.grouped_counts()
>   data.json_output()
>   data.search(filename)
>   elif week_choice == "previous week":
>   previous_data = functions2.dictionary()
>   filename = raw_input("What file do you want to use?")
>   previous_data.populate_dict(filename)
>   previous_data.total_counts()
>   previous_data.grouped_counts()
>   previous_data.json_output()
>   previous_data.search(filename)
>   else:
>   print "That choice is not correct"

The if, elif and else indentation is way off
Now that is probably due to emails being messed up,
but it makes it hard to give sensible feedback since
there could be bugs but we can't see them.sensibly...

Please be sure to send the complete error message
and not just summarize it and also use plain text,
especially when posting code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with error

2016-02-02 Thread Chelsea G
Hi,
When I run my code I am getting an error it says "Attribute Error:
Dictionary instance has no attribute 'search'. So the whole idea for my
code is to input a csv file and output results that we want. This specific
piece of code def search is to search the csv file for any keyword like
'issues' and output those results into a text file. I just need some help
with figuring out how to fix the error I am receiving.
This is my functions:

import csvimport jsonimport sysfrom collections import defaultdictfrom
collections import Counter
data = defaultdict(list)

upper_limit = 5
lower_limit = 4
class dictionary():
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.search_dict = defaultdict(list)

def populate_dict(self, filename):
with open(filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
self.dict[row[2]].append(row[3])

def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})

def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
new_list = str(total)
#self.total_dict.update({key: 'Total count for this
application: ' + str(total)})
#self.total_dict.update({key: str(total)})
self.total_dict[key].append(new_list)

def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
for value in c:
if c[value] >= upper_limit:
new_list = value, str(c[value])
self.grouped_dict[key].append(new_list)
elif c[value] <= lower_limit:
total += c[value]
self.other_dict.update({key: 'other: ' + str(total)})

for d in (self.grouped_dict, self.other_dict, self.total_dict):
for key, value in d.iteritems():
self.final_dict[key].append(value)

def json_output(self):
with open('test.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, indent = 4)

def search(self, filename):
with open(filename, 'r') as searchfile, open('weekly_test.txt', 
'w')
as search_results_file:
for line in searchfile:
if 'PBI 43125' in line:
print >>search_results_file, line



And then I have another python file where I import my functions and
run the results. Here is the code for that:

import functions2

week_choice = raw_input("Previous Week or Current Week?")if
week_choice == "current week":
data = functions2.dictionary()
filename = raw_input("What file do you want to use?")
data.populate_dict(filename)
data.total_counts()
data.grouped_counts()
data.json_output()
data.search(filename)
elif week_choice == "previous week":
previous_data = functions2.dictionary()
filename = raw_input("What file do you want to use?")
previous_data.populate_dict(filename)
previous_data.total_counts()
previous_data.grouped_counts()
previous_data.json_output()
previous_data.search(filename)
else:
print "That choice is not correct"


It says the error is with data.search(filename).. Not sure how to get
this working.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with error

2016-02-02 Thread Joel Goldstick
First, Please try to be more creative with your message subject line.
Help, isn't -- helpfull

Second.  Don't paraphrase the error, copy it from your actual terminal
screen and paste it here.

See below

On Tue, Feb 2, 2016 at 10:37 AM, Chelsea G  wrote:

> Hi,
> When I run my code I am getting an error it says "Attribute Error:
> Dictionary instance has no attribute 'search'. So the whole idea for my
> code is to input a csv file and output results that we want. This specific
> piece of code def search is to search the csv file for any keyword like
> 'issues' and output those results into a text file. I just need some help
> with figuring out how to fix the error I am receiving.
> This is my functions:
>
> import csvimport jsonimport sysfrom collections import defaultdictfrom
> collections import Counter
> data = defaultdict(list)
>
> upper_limit = 5
> lower_limit = 4
> class dictionary():
> def __init__(self):
> self.dict = defaultdict(list)
> self.counted_dict = defaultdict(list)
> self.grouped_dict = defaultdict(list)
> self.other_dict = defaultdict(list)
> self.final_dict = defaultdict(list)
> self.total_dict = defaultdict(list)
> self.search_dict = defaultdict(list)
>
> def populate_dict(self, filename):
> with open(filename, 'rb') as f:
> reader = csv.reader(f)
> next(reader, None)
> for row in reader:
> self.dict[row[2]].append(row[3])
>
> def all_counts(self):
> data_count = Counter()
> for key in self.dict.keys():
> self.counted_dict.update({key: Counter(self.dict[key])})
>
> def total_counts(self):
> for key in self.dict.keys():
> total = 0
> b = Counter(self.dict[key])
> for value in b:
> total += b[value]
> new_list = str(total)
> #self.total_dict.update({key: 'Total count for this
> application: ' + str(total)})
> #self.total_dict.update({key: str(total)})
> self.total_dict[key].append(new_list)
>
> def grouped_counts(self):
> for key in self.dict.keys():
> total = 0
> c = Counter(self.dict[key])
> for value in c:
> if c[value] >= upper_limit:
> new_list = value, str(c[value])
> self.grouped_dict[key].append(new_list)
> elif c[value] <= lower_limit:
> total += c[value]
> self.other_dict.update({key: 'other: ' + str(total)})
>
> for d in (self.grouped_dict, self.other_dict, self.total_dict):
> for key, value in d.iteritems():
> self.final_dict[key].append(value)
>
> def json_output(self):
> with open('test.txt', 'w') as text_file:
> json.dump(self.final_dict, text_file, sort_keys = True, indent
> = 4)
>
> Your search method below is indented so as to be a function within
json_output.  Remove the indentation so that it lines up with your other
class methods.


> def search(self, filename):
> with open(filename, 'r') as searchfile,
> open('weekly_test.txt', 'w')
> as search_results_file:
> for line in searchfile:
> if 'PBI 43125' in line:
> print >>search_results_file, line
>
>
>
> And then I have another python file where I import my functions and
> run the results. Here is the code for that:
>
> import functions2
>
> week_choice = raw_input("Previous Week or Current Week?")if
> week_choice == "current week":
> data = functions2.dictionary()
> filename = raw_input("What file do you want to use?")
> data.populate_dict(filename)
> data.total_counts()
> data.grouped_counts()
> data.json_output()
> data.search(filename)
> elif week_choice == "previous week":
> previous_data = functions2.dictionary()
> filename = raw_input("What file do you want to use?")
> previous_data.populate_dict(filename)
> previous_data.total_counts()
> previous_data.grouped_counts()
> previous_data.json_output()
> previous_data.search(filename)
> else:
> print "That choice is not correct"
>
>
> It says the error is with data.search(filename).. Not sure how to get
> this working.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with printing to text file

2016-02-01 Thread Steven D'Aprano
On Mon, Feb 01, 2016 at 08:41:31PM +, Alan Gauld wrote:
> On 01/02/16 14:07, Chelsea G wrote:
> > Hi,
> > 
> > So I am trying to get my function search to print  in a text file, but I
> > can only get it to print to Powershell. I have tried several things to get
> > it to print in its own text file but nothing I have tried is working. Can
> > someone tell me what I am doing wrong?

> That's because print sends its output to the standard out.
> You need to store your results somewhere (maybe in a list?) and
> then write() those results to a file.

You don't even need to do that! print has a secret (well, not really a 
secret, but you would be amazed how few people know about it) option to 
print directly to an open file.

In Python 3 you write:

print("Hello World!", file=output_file)

but in Python 2 you must use this ugly syntax instead:

print >>output_file, "Hello World!"

output_file must be already opened for writing, of course.

So Chelsea's class would become something like this:


class dictionary:
...
def search(self, filename):
with open('weekly_test.csv', 'r') as searchfile, 
open('testdoc.txt', 'w') as text_file:
for line in searchfile:
if 'PBI 43125' in line:
print >>text_file, line



By the way, the argument "filename" is not used here. Is that 
intentional?


But perhaps an even better solution is to use the environment's file 
redirection. Powershell should understand > to mean "print to a file", 
so you can write:

python myscript.py 

to have myscript print output directly to the terminal window, and then:

python myscript.py > testdoc.txt

to redirect the output and write it to testdoc.txt instead. 



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with printing to text file

2016-02-01 Thread Cameron Simpson

On 01Feb2016 20:41, ALAN GAULD  wrote:

On 01/02/16 14:07, Chelsea G wrote:

So I am trying to get my function search to print  in a text file, but I
can only get it to print to Powershell. I have tried several things to get
it to print in its own text file but nothing I have tried is working. Can
someone tell me what I am doing wrong?




class dictionary:
... 
def search(self, filename):
with open('weekly_test.csv', 'r') as searchfile:
for line in searchfile:
if 'PBI 43125' in line:
print line
with open('testdoc.txt', 'w') as text_file
text_file = searchfile


That's because print sends its output to the standard out.
You need to store your results somewhere (maybe in a list?) and
then write() those results to a file.


Or, of course, open the file and tell print to write there:

 with open('weekly_test.csv', 'r') as searchfile:
   with open('testdoc.txt', 'w') as text_file:
 ..
   print(line, file=text_file)

It looks like you're using python 2. To use the modern print syntax above you 
need:


 from __future__ import print_function

at the top of your python program. Python 3 uses the "function" form of print, 
and you need the above to tell python 2 to do so.


One advantage of Alan's "put it in a list" approach is that you could separate 
the seaching of the CSV into one function returning a list, and then do 
whatever you want (eg print it to your file) as a wholy separate operation.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with printing to text file

2016-02-01 Thread Joel Goldstick
On Mon, Feb 1, 2016 at 9:07 AM, Chelsea G  wrote:

> Hi,
>
> So I am trying to get my function search to print  in a text file, but I
> can only get it to print to Powershell. I have tried several things to get
> it to print in its own text file but nothing I have tried is working. Can
> someone tell me what I am doing wrong?
>
> import csvimport sysimport jsonfrom collections import defaultdictfrom
> collections import Counter
> data = defaultdict(list)
> mydict = defaultdict(list)
> class dictionary:
> def __init__(self):
> self.dict = defaultdict(list)
> self.counted_dict = defaultdict(list)
> self.grouped_dict = defaultdict(list)
> self.other_dict = defaultdict(list)
> self.final_dict = defaultdict(list)
> self.total_dict = defaultdict(list)
> self.search_dict = defaultdict(list)
>
>
> def populate_dict(self, filename):
> with open('weekly_test.csv', 'rb') as f:
> reader = csv.reader(f)
> next(reader, None)
> for row in reader:
> self.dict[row[2]].append(row[3])
>
>
> def total_counts(self):
> for key in self.dict.keys():
> total = 0
> b = Counter(self.dict[key])
> for value in b:
> total += b[value]
> self.total_dict.update({key: str(total)})
>
> def all_counts(self):
> data_count = Counter()
> for key in self.dict.keys():
> self.counted_dict.update({key:
> Counter(self.dict[key])})
>
>
> def grouped_counts(self):
> for key in self.dict.keys():
> total = 0
> c = Counter(self.dict[key])
> for value in c:
> if c[value] >= 5:
> self.grouped_dict.update({value:
> key + ': ' + str(c[value])})
>
> elif c[value] <= 4:
>
> total += c[value]
> self.other_dict.update({key:
> 'other: ' + str(total)})
>
> self.final_dict = self.grouped_dict,
> self.other_dict, self.total_dict
>
> def json_output(self):
> with open ('weekly2.txt', 'w') as text_file:
> json.dump(self.final_dict, text_file, sort_keys =
> True, indent = 4)
>
> def search(self, filename):
> with open('weekly_test.csv', 'r') as searchfile:
> for line in searchfile:
> if 'PBI 43125' in line:
> print line
>
i'm guessing above prints

> with open('testdoc.txt', 'w') as text_file
> text_file = searchfile
>

try something like this:

> def search(self, filename):
> with open('weekly_test.csv', 'r') as searchfile:
> with open('testdoc.txt', 'w') as text_file
> for line in searchfile:
> if 'PBI 43125' in line:
> text_file.write(line + '\n'

___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with printing to text file

2016-02-01 Thread Chelsea G
Hi,

So I am trying to get my function search to print  in a text file, but I
can only get it to print to Powershell. I have tried several things to get
it to print in its own text file but nothing I have tried is working. Can
someone tell me what I am doing wrong?

import csvimport sysimport jsonfrom collections import defaultdictfrom
collections import Counter
data = defaultdict(list)
mydict = defaultdict(list)
class dictionary:
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.search_dict = defaultdict(list)


def populate_dict(self, filename):  
with open('weekly_test.csv', 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
self.dict[row[2]].append(row[3])


def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})

def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})


def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + 
': ' + str(c[value])})

elif c[value] <= 4:

total += c[value]
self.other_dict.update({key: 'other: ' 
+ str(total)})

self.final_dict = self.grouped_dict, self.other_dict, 
self.total_dict   

def json_output(self):
with open ('weekly2.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, 
indent = 4)

def search(self, filename):
with open('weekly_test.csv', 'r') as searchfile:
for line in searchfile:
if 'PBI 43125' in line:
print line
with open('testdoc.txt', 'w') as text_file
text_file = searchfile
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with printing to text file

2016-02-01 Thread Alan Gauld
On 01/02/16 14:07, Chelsea G wrote:

> So I am trying to get my function search to print  in a text file, but I
> can only get it to print to Powershell. I have tried several things to get
> it to print in its own text file but nothing I have tried is working. Can
> someone tell me what I am doing wrong?

I meant to add in my other reply that you could combine the
reading and writing into a single 'with' block and thus avoid
creating the intermediate list. That could save important
memory if searchfile is a big file.

You can open 2 files in a single with statement:

with open('foo.txt','r') as infile, open ('bar.txt','w') as outfile:
for line in infile:
if searchstring in line:
outfile.write(line)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with printing to text file

2016-02-01 Thread Alan Gauld
On 01/02/16 14:07, Chelsea G wrote:
> Hi,
> 
> So I am trying to get my function search to print  in a text file, but I
> can only get it to print to Powershell. I have tried several things to get
> it to print in its own text file but nothing I have tried is working. Can
> someone tell me what I am doing wrong?
> 

> class dictionary:
>   ... 
>   def search(self, filename):
>   with open('weekly_test.csv', 'r') as searchfile:
>   for line in searchfile:
>   if 'PBI 43125' in line:
>   print line
>   with open('testdoc.txt', 'w') as text_file
>   text_file = searchfile

That's because print sends its output to the standard out.
You need to store your results somewhere (maybe in a list?) and
then write() those results to a file.

Note that searchfile is only open within the first 'with' section,
it is automatically closed when you leave the with block.
So assigning searchfile to textfile is never going top work.
Even if it did, searchfile is read-only so you couldn't write to it.

So to make it work you need to

1) replace the print line with a line that appends the result
   to a list.

2) replace the textfile assignment with a loop that writes
   each entry in your list to textfile. (You may need to
   append a newline \n at the end of each line)

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2016-01-26 Thread boB Stepp
In case you cannot see what we are talking about in how your message
is not keeping its proper indentation, go to the Tutor Mail Archive
at:

https://www.mail-archive.com/tutor@python.org/msg73411.html

and perhaps you can better see the difficulty we are having reading
your message.

boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help

2016-01-26 Thread Alan Gauld
On 26/01/16 20:57, Chelsea G wrote:
> ...I have the basic code for it...

Sorry, when I said paste it in the message I should have
also pointed out that you need to ensure the mail tool
is sending plain text, otherwise we lose all indentation.

But this looks like the same code as before so I'm
guessing you haven't fixed those issues I raised
last time?

Alan G.

> import csv
> import json
> import sys
> from collections import defaultdict
> from collections import Counter
> 
> 
> class dictionary():
> def __init__(self):
> self.dict = defaultdict(list)
> self.counted_dict = defaultdict(list)
> self.grouped_dict = defaultdict(list)
> self.other_dict = defaultdict(list)
> self.final_dict = defaultdict(list)
> self.total_dict = defaultdict(list)
> self.search_dict = defaultdict(list)
> mydict = defaultdict(list)
> def populate_dict(self, filename):
> with open (filename, 'rb') as f:
> reader = csv.reader(f)
> next(reader, None)
> for row in reader:
> self.dict[row[2]].append(row[3])
...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help

2016-01-26 Thread Chelsea G
Hi,
I am working on a python script to automate reporting. And I am working on
creating a keyword search. For example, if I want to search for the word
Tool in the value and see what keys are associated with that. So say the
value I have to search is Tool World and I want to know what key is
associated with Tool World I search Tool World and it comes up with several
results like missing or not updating and catalog issue. I have the basic
code for it figured out but I have created my own dictionary for it called
mydict and put a few key and values in but I want my code to search the csv
file that I am importing and then take the info I am getting from the
search results and put it in its own text file. Also, I dont want to have
to create the mydict line with the keywords I want to be able to type in a
value like Tool and search through the csv file and then output the results
to a text file. So I guess what I want to do is take the row 2 and row 3
from the csv file and output that to text file then from there create a
keyword search and output the results to another text file.

import csv
import json
import sys
from collections import defaultdict
from collections import Counter


class dictionary():
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.search_dict = defaultdict(list)
mydict = defaultdict(list)
def populate_dict(self, filename):
with open (filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
self.dict[row[2]].append(row[3])
def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})
def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})
def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + ': ' + str(c[value])})
elif c[value] <= 4:
total += c[value]
self.other_dict.update({key: 'other: ' + str(total)})
self.final_dict = self.grouped_dict, self.other_dict, self.total_dict
#mydict = {'Project Tool Issue': ['CPO Project Tool'], 'All catalogs
missing or not updating': ['20/20 Design Tool']}
def search(mydict, lookup):
for key, value in mydict.iteritems():
for v in value:
if lookup in v:
#return key
print key
search(mydict, 'Tool')
# def txt_output(self, filename):
# a = filename.split('.')
# self.txt_output = a + '.txt'
# print a
def json_output(self):
with open ('scripttesting.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, indent = 4)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help!

2016-01-26 Thread Alan Gauld
On 26/01/16 18:05, Chelsea G wrote:

> creating a keyword search. For example, if I want to search for the word
> Tool in the value and see what keys are associated with that. So say the
> value I have to search is Tool World and I want to know what key is
> associated with Tool World I search Tool World and it comes up with several
> results like missing or not updating and catalog issue. 


> I have the basic code for it figured out

Not if its the code you attached you haven't.
It won't do anything because all of the code is inside
the class definition.  So until you create an instance
of the class nothing will happen.

And that's assuming there are no other errors, and I'm
pretty sure I can see at least 1 more.

> ... I want my code to search the csv
> file that I am importing and then take the info I am getting from the
> search results and put it in its own text file. Also, I dont want to have
> to create the mydict line with the keywords I want to be able to type in a
> value like Tool and search through the csv file and then output the results
> to a text file. I have attached my code.

That's all fine and dandy but do it one piece at a time,
don't try to make a huge program work all at once.
Pick one thing and get it working.
I suggest:
1) load the csv file into a dict and print out the result.
2) implement user entry of a dict item, print the result
3) implement the search, print the found items value(s)
4) output the results to a text file (BTW why have you
   JSON functions if you want a text file? Or do you
   really mean a JSON file?

Bite it off one bit at a time. It's much easier to modify
working code than to fix everything at once.

BTW you were lucky your attachment made it through.
The list server often loses them. Its not a lot of code
so just paste it into your mail messages. Its much easier
for us to see and respond to that way.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help!

2016-01-26 Thread Joel Goldstick
On Tue, Jan 26, 2016 at 1:05 PM, Chelsea G  wrote:

> Hi,
> I am working on a python script to automate reporting. And I am working on
> creating a keyword search. For example, if I want to search for the word
> Tool in the value and see what keys are associated with that. So say the
> value I have to search is Tool World and I want to know what key is
> associated with Tool World I search Tool World and it comes up with several
> results like missing or not updating and catalog issue. I have the basic
> code for it figured out but I have created my own dictionary for it called
> mydict and put a few key and values in but I want my code to search the csv
> file that I am importing and then take the info I am getting from the
> search results and put it in its own text file. Also, I dont want to have
> to create the mydict line with the keywords I want to be able to type in a
> value like Tool and ursearch through the csv file and then output the
> results
> to a text file. I have attached my code.
>
> Welcome!  You can paste your code in your question.  People can't or won't
read attachments here, so for better help try to cut the code to show the
issue or problem, then paste it.

I'm not quite sure I understand what you want to create.  Could you give a
snippet of a typical csv file that you want to examine?  And the format and
substance of the output you wish to create?

> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Joel Goldstick
http://joelgoldstick.com/stats/birthdays
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] help!

2016-01-26 Thread Chelsea G
Hi,
I am working on a python script to automate reporting. And I am working on
creating a keyword search. For example, if I want to search for the word
Tool in the value and see what keys are associated with that. So say the
value I have to search is Tool World and I want to know what key is
associated with Tool World I search Tool World and it comes up with several
results like missing or not updating and catalog issue. I have the basic
code for it figured out but I have created my own dictionary for it called
mydict and put a few key and values in but I want my code to search the csv
file that I am importing and then take the info I am getting from the
search results and put it in its own text file. Also, I dont want to have
to create the mydict line with the keywords I want to be able to type in a
value like Tool and search through the csv file and then output the results
to a text file. I have attached my code.
import csv 
import json 
import sys 
from collections import defaultdict 
from collections import Counter 


class dictionary(): 
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.search_dict = defaultdict(list)


def populate_dict(self, filename):
with open (filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None) 
for row in reader:
self.dict[row[2]].append(row[3]) 



def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})

def all_counts(self):
data_count = Counter()
for key in self.dict.keys(): 
self.counted_dict.update({key: Counter(self.dict[key])})


def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key]) 
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + 
': ' + str(c[value])})

elif c[value] <= 4:

total += c[value]
self.other_dict.update({key: 'other: ' 
+ str(total)})

self.final_dict = self.grouped_dict, self.other_dict, 
self.total_dict

mydict = {'Project Tool Issue': ['CPO Project Tool'], 'All catalogs 
missing or not updating': ['20/20 Design Tool']}
def search(mydict, lookup):
for key, value in mydict.iteritems():
for v in value:
if lookup in v:
 #return key
print key

search(mydict, 'Tool')


# def txt_output(self, filename):
# a = filename.split('.')
# self.txt_output = a + '.txt'
# print a






def json_output(self):
with open ('scripttesting.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, 
indent = 4)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help!

2016-01-26 Thread Chelsea G
Hi,
I am working on a python script to automate reporting. And I am working on
creating a keyword search. For example, if I want to search for the word
Tool in the value and see what keys are associated with that. So say the
value I have to search is Tool World and I want to know what key is
associated with Tool World I search Tool World and it comes up with several
results like missing or not updating and catalog issue. I have the basic
code for it figured out but I have created my own dictionary for it called
mydict and put a few key and values in but I want my code to search the csv
file that I am importing and then take the info I am getting from the
search results and put it in its own text file. I have attached my document.
import csv 
import json 
import sys 
from collections import defaultdict 
from collections import Counter 


class dictionary(): 
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.search_dict = defaultdict(list)




def populate_dict(self, filename):
with open (filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None) 
for row in reader:
self.dict[row[2]].append(row[3])  

def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})

def all_counts(self):
data_count = Counter()
for key in self.dict.keys(): 
self.counted_dict.update({key: Counter(self.dict[key])})


def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key]) 
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + 
': ' + str(c[value])})

elif c[value] <= 4:

total += c[value]
self.other_dict.update({key: 'other: ' 
+ str(total)})

self.final_dict = self.grouped_dict, self.other_dict, 
self.total_dict

mydict = {'Project Tool Issue': ['CPO Project Tool'], 'All catalogs 
missing or not updating': ['20/20 Design Tool']}
def search(mydict, lookup):
for key, value in mydict.iteritems():
for v in value:
if lookup in v:
#return key
print key

search(mydict, 'Tool')


# def txt_output(self, filename):
# a = filename.split('.')
# self.txt_output = a + '.txt'
# print a






def json_output(self):
with open ('testing.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, 
indent = 4)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help!

2016-01-25 Thread Alan Gauld
On 25/01/16 17:39, Chelsea G wrote:
> Hi,
> I am trying to create a keyword search, so that someone can type in  a key
> phrase and then the output be the value with the key. 

I'm not completely clear what you mean by a key phrase?
Do you mean a phrase matching the keys in your dictionary?(In which case
its easy) or domyou mean a random phrase? In which case what should happen?

> I have some code
> already done but having some trouble getting it to work.

Sadly you haven't posted in plain text so its lost all indentation,
making it nearly unreadable. Can you repost in plain text please?

> class dictionary():
> def __init__(self):
> self.dict = defaultdict(list)
> self.counted_dict = defaultdict(list)
> self.grouped_dict = defaultdict(list)
> self.other_dict = defaultdict(list)
> self.final_dict = defaultdict(list)
> self.total_dict = defaultdict(list)
> self.keyword_dict = defaultdict(list)
> def populate_dict(self, filename):
> with open (filename, 'rb') as f:
> reader = csv.reader(f)
> next(reader, None)
> for row in reader:
> self.dict[row[2]].append(row[3])
...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help!

2016-01-25 Thread Chelsea G
Hi,
I am trying to create a keyword search, so that someone can type in  a key
phrase and then the output be the value with the key. I have some code
already done but having some trouble getting it to work.
import csv
import json
import sys
from collections import defaultdict
from collections import Counter


class dictionary():
def __init__(self):
self.dict = defaultdict(list)
self.counted_dict = defaultdict(list)
self.grouped_dict = defaultdict(list)
self.other_dict = defaultdict(list)
self.final_dict = defaultdict(list)
self.total_dict = defaultdict(list)
self.keyword_dict = defaultdict(list)
def populate_dict(self, filename):
with open (filename, 'rb') as f:
reader = csv.reader(f)
next(reader, None)
for row in reader:
self.dict[row[2]].append(row[3])
def total_counts(self):
for key in self.dict.keys():
total = 0
b = Counter(self.dict[key])
for value in b:
total += b[value]
self.total_dict.update({key: str(total)})
def all_counts(self):
data_count = Counter()
for key in self.dict.keys():
self.counted_dict.update({key: Counter(self.dict[key])})
def grouped_counts(self):
for key in self.dict.keys():
total = 0
c = Counter(self.dict[key])
for value in c:
if c[value] >= 5:
self.grouped_dict.update({value: key + ': ' + str(c[value])})
elif c[value] <= 4:
total += c[value]
self.other_dict.update({key: 'other: ' + str(total)})
self.final_dict = self.grouped_dict, self.other_dict, self.total_dict

def keyword_items(defaultdict, lookup):
defaultdict = {' Tool Issue': ['Project Tool'], 'All catalogs missing or
not updating': ['Design Tool']}
for value, key in defaultdict.items():
for v in value:
if lookup in v:
return key
def json_output(self):
with open ('testing.txt', 'w') as text_file:
json.dump(self.final_dict, text_file, sort_keys = True, indent = 4)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help!

2016-01-17 Thread Steven D'Aprano
On Fri, Jan 15, 2016 at 11:33:24AM -0500, Chelsea G wrote:
> Hi,

[snip stuff which is, as far as I can see, irrelevant]

> What I am having issues with is the def txt_output that is where I am
> trying to take the .csv off and add the .txt but keep the filename the
> same. For example, having a filename "weekly_20160102.csv" and then create
> a txt filename with "weekly_20160102.txt" and have all the counts and
> products in the text file. Is there any way to do this?


This is how to change the file extension:

py> import os
py> filename = "weekly_20160102.csv"
py> newname = os.path.splitext(filename)[0] + ".txt"
py> print(newname)
weekly_20160102.txt


Once you have the new file name, ending with .txt, do you understand how 
to open it and write to it? For example, you might do this:

with open(newname, "w") as f:
f.write("line 1\n")
f.write("second line\n")
f.write("last line\n")


When you exit the "with" block, the file will be automatically closed.

Remember to use \n (newline) at the end of each line.


-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


<    1   2   3   4   5   6   7   8   9   10   >