Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Alan Gauld
"Tim Michelsen" <[EMAIL PROTECTED]> wrote in 

>> Another option is to have the config settiongs in a normal
>> Python module and just import it. 

> I think that the cfg-files are much more readable for others.

More readable than:

# Section Heading
variable = value

It looks pretty easy to read to me! :-)

If its very complex you can use dictionaries:

SectionFoo = {
firstName : theValue
second  : anotherValue
}

Which is still pretty easy for the casual reader/maintainer 
and allows access like:

import myconfig
foo2 = myconfig.SectionFoo['second']

Just a thought.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Open url in browser window

2008-04-15 Thread Alan Gauld
"Michael Finlayson" <[EMAIL PROTECTED]> wrote

> I would like to ask the group if it is even possible
> on a Mac before I go through learning Python.

This has less to do with Python than with Macs

Which browser are you thinking of using?
Mac users have a variety with Safari the most
common along with Firefox and IE for Mac.
But Opera and several others also exist.
I think Safari and IE are installed by default.
But any or all of them could be removed by
the user. (For example I removed IE since
its not very good on a MAC IMHO!)

Or do you install your own browser within
your application?

> We use this approach for several reasons.
> For the security of our training and the security
> of our clients computers,

The latter claim is a bit spurious, if they weren't
secure before launching your app they are
unlikely to be more secure during the running
of it! Especially if there are processes running
in the background or orther users logged in - MacOS
is a true multi user/multi tasking OS after all,
there may be several simultaneous users on
any machine.

> We do this by opening a browser window of
> a specific size with no url line, no menus, nothing except
> scroll bars, if necessary.

That will be totally browser dependant.

> Also, to discourage trainees from skipping out of
> the training to launch other applications, we also
> disable the tab key and control/alt/delete.

Thee are equivalents on a mac. I assume you also
make your app full screen and remove menus etc?
ie use kiosk view? That is presumably possible on
MacOS but recall that the menu bar in MacOS is
not attached to the app window.

> Are either or both of these possible on a Mac
> using Python?

If its possible on a Mac its almost certainly
possible via Python. The programming language
isn't your issue here, its what does MacOS and the
browser support?

> 1.   Control the default browser parameters
> (like you can setup popup windows in javascript
> with the onClick="MM_openBrWindow command)

Depends on the browser.

> 2.   Control of the user’s keyboard.

Yes that should be possible but it might involve a lot
of work catching all the possible exit codes on a Mac.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Recursion doubt

2008-04-15 Thread Anshu Raval

Hi, 
At the url http://www.python.org/doc/essays/graphs.html there is some code by 
Guido Van Rossum for computing paths through a graph - I have pasted it below 
for reference - 
Let's write a simple function to determine a path between two nodes. It takes a 
graph and the start and end nodes as arguments. It will return a list of nodes 
(including the start and end nodes) comprising the path. When no path can be 
found, it returns None. The same node will not occur more than once on the path 
returned (i.e. it won't contain cycles). The algorithm uses an important 
technique called backtracking: it tries each possibility in turn until it finds 
a solution. 
def find_path(graph, start, end, path=[]): path = path + [start]
 if start == end: return path if not 
graph.has_key(start): return None for node in graph[start]: 
if node not in path: newpath = find_path(graph, 
node, end, path) if newpath: return newpath return None 
*** He then says 
It is simple to change this function to return a list of all paths (without 
cycles) instead of the first path it finds: 
def find_all_paths(graph, start, end, path=[]): path = path + 
[start] if start == end: return [path] if not 
graph.has_key(start): return [] paths = [] for node 
in graph[start]: if node not in path: newpaths = 
find_all_paths(graph, node, end, path) for newpath in newpaths: 
paths.append(newpath) return paths 
*** I couldn't understand how it was simple to change the function find paths 
to find all paths. How would you think about writing this second function 
recursively. Especially the part about if start==end: return [path]. I feel you 
would give square brackets around path here after first writing the inductive 
part ... for node in graph[start]  and then by trial and error put square 
brackets around path in the Basis part. Can someone please explain how to write 
this code. Thanks! 
_
Video: Get a glimpse of the latest in Cricket, Bollywood, News and Fashion. 
Only on MSN videos.
http://video.msn.com/?mkt=en-in___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Error with incorrect encoding

2008-04-15 Thread Oleg Oltar
I am trying to parse an html page. Have following error while doing that


 src = sel.get_html_source()
links = re.findall(r'', src)
for link in links:
print link



==
ERROR: test_new (__main__.NewTest)
--
Traceback (most recent call last):
  File "", line 19, in test_new
UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in
position 90: ordinal not in range(128)

--
Ran 1 test in 6.345s
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error with incorrect encoding

2008-04-15 Thread Kent Johnson
Oleg Oltar wrote:
> I am trying to parse an html page. Have following error while doing that
> 
> 
>  src = sel.get_html_source()
> links = re.findall(r'', src)
> for link in links:
> print link

Presumably get_html_source() is returning unicode? So link is a unicode 
string. To print, unicode must be encoded somehow. By default Python 
will try to encode as ascii, which causes the failure you are seeing.

Try
   print link.encode('xxx')
where 'xxx' is the value of sys.stdout.encoding, most likely either 
'utf-8' or 'windows-1252' depending on your platform.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Tim Michelsen
>>> Another option is to have the config settiongs in a normal
>>> Python module and just import it. 
> 
>> I think that the cfg-files are much more readable for others.
> 
> More readable than:
> 
> # Section Heading
> variable = value
> 
> It looks pretty easy to read to me! :-)
> 
> If its very complex you can use dictionaries:
> 
> SectionFoo = {
> firstName : theValue
> second  : anotherValue
> }
> 
> Which is still pretty easy for the casual reader/maintainer 
> and allows access like:
> 
> import myconfig
> foo2 = myconfig.SectionFoo['second']
This seems like reinventing what the ConfigParser mdoule [1] already does.

I think I will read the config file once and the provide the parameters 
with a settings.py module throughout the program and the modules.
Sounds like doing it twice.
But to my optinion Config Parser offers the following advantage:
- Readable
- All are strings => no strange 'mysetting' is needed.

Thanks for your help.

Kind regards,
Timmie

[1]http://docs.python.org/lib/module-ConfigParser.html

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Alan Gauld
"Tim Michelsen" <[EMAIL PROTECTED]> wrote

>> import myconfig
>> foo2 = myconfig.SectionFoo['second']
> This seems like reinventing what the ConfigParser 
> mdoule [1] already does.

But with the advantage that its pure python, no parsing 
needed so its both faster and avouds any string to int 
type conversions

> But to my optinion Config Parser offers the following advantage:
> - Readable
> - All are strings => no strange 'mysetting' is needed.

I'm not sure what you mean. The Python variables and dictionary 
is all strings too. mysetting is just a string...

But the choice is yours, you can use config parser to parse 
a config file into variables in a settings module or you can 
create the settings directly in the settings module.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Kent Johnson
Alan Gauld wrote:

>> But to my optinion Config Parser offers the following advantage:
>> - Readable
>> - All are strings => no strange 'mysetting' is needed.
> 
> I'm not sure what you mean. The Python variables and dictionary 
> is all strings too. mysetting is just a string...

He means, with ConfigParser strings don't need to be quoted, giving 
perhaps a cleaner and more friendly syntax.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] datetime module problem

2008-04-15 Thread Dick Moores


I'm really struggling with the datetime module. Trying for a script that
will calculate the number of days between any two dates, I've come up
with this:
import datetime
date1 = raw_input("Enter date1 as year-month-day: ")
year1, month1, day1 = date1.split('-')
date1 = datetime.date(int(year1), int(month1), int(day1))
date2 = raw_input("Enter date2 as year-month-day: ")
year2, month2, day2 = date2.split('-')
date2 = datetime.date(int(year2), int(month2), int(day2))
print "date2 - date1 is", date2 - date1
Here's one run:
Enter date1 as year-month-day: 2003-4-15
Enter date2 as year-month-day: 2008-4-15
date2 - date1 is 1827 days, 0:00:00
How can I get rid of that "0:00:00"?
And there must be a better way. What is it?
Thanks,
Dick Moores

  

UliPad <>:

http://code.google.com/p/ulipad/


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] datetime module problem

2008-04-15 Thread bob gailer
Dick Moores wrote:
> I'm really struggling with the datetime module. Trying for a script 
> that will calculate the number of days between any two dates, I've 
> come up with this:
>
> import datetime
> date1 = raw_input("Enter date1 as year-month-day: ")
> year1, month1, day1 = date1.split('-')
> date1 = datetime.date(int(year1), int(month1), int(day1))
> date2 = raw_input("Enter date2 as year-month-day: ")
> year2, month2, day2 = date2.split('-')
> date2 = datetime.date(int(year2), int(month2), int(day2))
> print "date2 - date1 is", date2 - date1
>
> Here's one run:
> Enter date1 as year-month-day: 2003-4-15
> Enter date2 as year-month-day: 2008-4-15
> date2 - date1 is 1827 days, 0:00:00
>
> How can I get rid of that "0:00:00"?
>
> And there must be a better way. What is it?

You might read the datetime documentation.

And then notice that date2 - date1 is a timedelta object.

And then look that up to see its attributes (which inculdes days)

And then try print (date2 - date1).days

-- 
Bob Gailer
919-636-4239 Chapel Hill, NC

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] datetime module problem

2008-04-15 Thread Kent Johnson
Dick Moores wrote:
> I'm really struggling with the datetime module. Trying for a script that 
> will calculate the number of days between any two dates

How about this:

from datetime import datetime
date1 = raw_input("Enter date1 as year-month-day: ")
date1 = datetime.strptime(date1, '%Y-%m-%d')
date2 = raw_input("Enter date2 as year-month-day: ")
date2 = datetime.strptime(date2, '%Y-%m-%d')
print "date2 - date1 is", (date2 - date1).days, 'days'

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Alan Gauld

"Kent Johnson" <[EMAIL PROTECTED]> wrote

>> I'm not sure what you mean. The Python variables and dictionary
>> is all strings too. mysetting is just a string...
>
> He means, with ConfigParser strings don't need to be quoted, giving
> perhaps a cleaner and more friendly syntax.

Ah, I see, yes that's a valid point.

The whole issue of security is worth considering too. If the
config file is not controlled then it is open to abuse since it
allows a lot more than the simple set of name/value assignments
that ConfigParser does.
(I meant to mention that earlier)

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] setting program configuration for all files and modules ofa program

2008-04-15 Thread Tim Michelsen
>>> But to my optinion Config Parser offers the following advantage:
>>> - Readable
>>> - All are strings => no strange 'mysetting' is needed.
>> I'm not sure what you mean. The Python variables and dictionary 
>> is all strings too. mysetting is just a string...
> 
> He means, with ConfigParser strings don't need to be quoted, giving 
> perhaps a cleaner and more friendly syntax.
Yes, Kent that's what I wanted to express.
Thanks for clarifying.
My target here are users that do not develop python.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-15 Thread Ricardo Aráoz
> Malcolm Greene wrote:
>> What is the Pythonic way to remove specific chars from a string? The
>> .translate( table[, deletechars]) method seems the most 'politically
>> correct' and also the most complicated.

Why complicated?


import string
myStr = 'some text from which you want to delete some chars'
resultStr = s.translate(string.maketrans('', ''), 'nem')
print resultStr

Output : so txt fro which you wat to dlt so chars

You just have to use maketrans with empty strings. If string is 
deprecated then I guess some other way of creating translation tables 
will be provided.

HTH

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cut all decimal places with zeros

2008-04-15 Thread Tim Michelsen
>> how can I suppress the decimal places for (only those) numbers whos 
>> decimal places are zero (0)?
> 
> I don't know how to do this with just string formatting but I think
> ('%.4f' % n).rstrip('.0')
> will do what you want.
No.
I tested with
n = 10.0
You code returns '1'

My code returns '10'

Here again:
### CODE ###
def cut_decimals(float):
"""
input: floating number
output: number as string with zero decimals removed
"""
#print float-int(float)
#print '%.4f' %float
if float-int(float) != 0:
number =  '%.4f' %float
number = number.replace('0.','X.')
number = number.replace('0','')
number = number.replace('X.','0.')
else:
number =  '%.0f' %float
return number
 END ###

Regards,
Timmie

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] datetime module problem

2008-04-15 Thread Dick Moores
At 02:37 PM 4/15/2008, Kent Johnson wrote:
>Dick Moores wrote:
>>I'm really struggling with the datetime module. Trying for a script 
>>that will calculate the number of days between any two dates
>
>How about this:
>
>from datetime import datetime
>date1 = raw_input("Enter date1 as year-month-day: ")
>date1 = datetime.strptime(date1, '%Y-%m-%d')
>date2 = raw_input("Enter date2 as year-month-day: ")
>date2 = datetime.strptime(date2, '%Y-%m-%d')
>print "date2 - date1 is", (date2 - date1).days, 'days'
>
>Kent

Yes, thanks, Kent.

I finally tracked down that table for the format string, at 
. Been experimenting 
with it. Realized that the format string could be the more familiar 
American '%m/%d/%Y', or '%m/%d/%y'.

The docs are so hard for me to understand, that I'm even feeling 
pleased with myself for this:

from datetime import datetime
date1 = raw_input("Enter date1 as year-month-day: ")
date1 = datetime.strptime(date1, '%m/%d/%Y')
today = datetime.now()
print "today - date1 is", (today - date1).days, 'days'

Dick



UliPad <>: http://code.google.com/p/ulipad/ 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cut all decimal places with zeros

2008-04-15 Thread John Fouhy
On 16/04/2008, Tim Michelsen <[EMAIL PROTECTED]> wrote:
> Kent wrote:
>  > I don't know how to do this with just string formatting but I think
>  > ('%.4f' % n).rstrip('.0')
>  > will do what you want.
>
> No.
>  I tested with
>  n = 10.0
>  You code returns '1'
>
>  My code returns '10'

Good catch.  Try:

('%.4f' % n).rstrip('0').rstrip('.')

You can read about the rstrip function by starting the python
interpreter, then typing
  help(''.rstrip)

This will explain that rstrip will strip off any charcters in the
argument from the right of the string you call it on.

So '10.0'.rstrip('.0') will remove any '.' or '0' from the right, leaving '1'.

'10.0'.rstrip('0') will remove '0' only, leaving '10.'.  Thus
'10.0'.rstrip('0').rstrip('.') will remove the '0's, then remove the
'.'s, leaving '10'.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove specific chars from a string

2008-04-15 Thread John Fouhy
On 16/04/2008, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>  You just have to use maketrans with empty strings. If string is
>  deprecated then I guess some other way of creating translation tables
>  will be provided.

Most string.* functions are deprecated, because they've been moved to
methods of strings. (e.g. string.capitalize(s) --> s.capitalize())

But that doesn't work for a couple of functions, like maketrans, so
those functions are not deprecated.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Test - please ignore

2008-04-15 Thread bob gailer




Just testing as recently I'm not seeing my posts even though Receive
your own posts to the list? is Yes.
-- 
Bob Gailer
919-636-4239 Chapel Hill, NC



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Nested dictionary with defaultdict

2008-04-15 Thread GTXY20
Hi tutors,

I currently have a dictionary like the following:

{'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3':
['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
['238', '238'], '7': ['220']}

I am trying to create a dictionary that would list the current key and a
count of the iterations of values within the value list like so:

{'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: {
'238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' :
2}, '7': {'220' : 1}}

Now I am pretty sure that I need to loop through the first dictionary and
create a defaultdict from the values for each key in that dictionary but at
this point I am having difficulty coming up with the loop.

I am looking for a satrting point or any suggestions.

Many thanks in advance.

GTXY20
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread Marc Tompkins
Does anyone out have experience with:
-  manipulating RTF files?
-  or writing OpenOffice macros in Python?

I need to pre-process approximately 10,000 medical reports so they can be
imported into an EMR.  (They were originally saved as Word .docs; I'd like
to give hearty thanks to the authors of "ooconvert" (
http://sourceforge.net/projects/ooconvert/), which enabled me to do a batch
conversion with much less effort than I was expecting...)

Anyway, the files as they now exist each contain a single section, with a
header and footer on each page.
The EMR's import function wants to see a slug of summary information as the
first thing on the first page, which means that the header needs to be
suppressed; however, I expect that the users will want to reprint these
things in the future, so I don't want to delete the header entirely.  In
short, what I want to do is insert a new section at the top of the file.

My tasks are:
- figure out which codes I need to insert to create a new section with no
header and then re-enable it at the end
- figure out where in the file to do the inserting (I thought I already had
this worked out, but apparently not quite)
THEN
- figure out how to find the correct insertion point programmatically -
either agnostically, by finding a particular pattern of symbols that occur
in the right location, or by actually parsing the RTF hierarchy to figure
out where the meta-document ends and the document begins.  The agnostic
solution would be much easier - and this is a one-off, so I'm not building
for the ages here - but it really looks like homogeneous tag soup to me.  I
have, of course, tried inserting the section myself and then compared the
before-and-after files... but all I've got so far is a headache...  (Not
quite true - I think I'm close - but I'm getting angrier with Microsoft with
every moment I spend looking at this stuff.  Hyper-optimized Perl is a
freakin' marvel of clarity next to this... )
{\footerr \ltrpar \pard\plain \ltrpar\s22\qc
\li0\ri0\nowidctlpar\tqc\tx4153\tqr\tx8306\wrapdefault\faauto\rin0\lin0\itap0
\rtlch\fcs1 \af0\afs20\alang1025 \ltrch\fcs0
\fs24\lang3081\langfe255\cgrid\langnp3081\langfenp255
{\rtlch\fcs1 \af0 \ltrch\fcs0 \f1\fs16\insrsid5703726 \par }
\pard \ltrpar\s22\qc
\li0\ri0\nowidctlpar\tqc\tx4153\tqr\tx8306\wrapdefault\faauto\rin0\lin0\itap0\pararsid5703726

{\rtlch\fcs1 \af0\afs24 \ltrch\fcs0
\fs16\lang3081\langfe1033\loch\af1\hich\af43\langfenp1033\insrsid5703726
GAAAHHH!

It occurs to me that there might be another way - maybe I can automate
OpenOffice to open each file and insert the blank section and some dummy
text, and then, in Python, find the dummy text and replace it with the
summary slug?   Maybe even do the whole job with a macro?  And never have to
poke through RTF again?

So I was juggling the RTF spec (the RTFM?), a text editor, Word (so I can
make sure the thing still looks right), and the import utility - when it
suddenly struck me that someone out there may have done this before.  (And
yes, I've definitely Googled, but my Google-fu may be weak today.)  If
anyone has insight into RTF Zen, or has some tips on batch macros in oO, I'd
be obliged...

Marc
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread John Fouhy
On 16/04/2008, Marc Tompkins <[EMAIL PROTECTED]> wrote:
> Does anyone out have experience with:
> -  manipulating RTF files?

Is this any help to you: http://pyrtf.sourceforge.net/

?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread python
Mark,

Here's how we work with RTF: We create a Word document formatted exactly
like we want with special markers (unique text) inserted in places where
we want to programmatically add text.

We save this document to RTF (this RTF becomes our template file),
remove all the carriage returns and line feeds, and then replace our
marker text with the text we want to insert.

Each new version of Word introduces new RTF codes and markup patterns.

Recommendation: Find a very old version of Word (Word 95) to generate
your RTF 'templates'. The older versions of Word generate much simpler
RTF that is forward compatible.

Good luck!
Malcolm
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested dictionary with defaultdict

2008-04-15 Thread Kent Johnson
GTXY20 wrote:
> 
> Hi tutors,
> 
> I currently have a dictionary like the following:
> 
> {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], 
> '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], 
> '6': ['238', '238'], '7': ['220']}
> 
> I am trying to create a dictionary that would list the current key and a 
> count of the iterations of values within the value list like so:
> 
> {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: 
> { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': 
> {'238' : 2}, '7': {'220' : 1}}

?? Do you really want keys of '2' and 2? How can you have two keys '5'? 
I guess maybe you want
{'1': {'220' : 3}, '2': {'220' : 1, 238 : 4}, '3': {'220' : 1, '238' : 
1}, '4': {220 : 2}, '5': {'220: 2, 238 : 1}, '6': {'238' : 2}, '7': 
{'220' : 1}}

> Now I am pretty sure that I need to loop through the first dictionary 
> and create a defaultdict from the values for each key in that dictionary 
> but at this point I am having difficulty coming up with the loop.
> 
> I am looking for a satrting point or any suggestions.

Do you know how to turn
['220', '238', '238', '238', '238']
into
{'220' : 1, '238' : 4}
?

If so, then put that code in a loop over the key, value pairs of the dict.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested dictionary with defaultdict

2008-04-15 Thread John Fouhy
On 16/04/2008, GTXY20 <[EMAIL PROTECTED]> wrote:
> I currently have a dictionary like the following:
>
> {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3':
> ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
> ['238', '238'], '7': ['220']}
>
> I am trying to create a dictionary that would list the current key and a
> count of the iterations of values within the value list like so:
>
> {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: {
> '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' :
> 2}, '7': {'220' : 1}}
[...]
> I am looking for a satrting point or any suggestions.

Can you write a function that will take a list and return a dictionary
with the counts of elements in the list?

i.e. something like:

>>> def countValues(valueList):
...  # your code goes here
...
>>> countValues(['220', '238', '238', '238', '238'])
{'238': 4, '220': 1}

P.S.  Your sample output is not a valid dictionary...

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested dictionary with defaultdict

2008-04-15 Thread GTXY20
Hi Kent,

Yes I think so I think I am almost there with this:

from collections import defaultdict
d = {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
'3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
['238', '238'], '7': ['220']}

for f, b in d.items():
h = defaultdict(int)
for j in b:
h[j]+=1
print ('%s, %s' % (f, h))

However, not exactly happy with the printed output as soon as I complete I
will repost what I come up with.

Thanks so much.

M.

On Tue, Apr 15, 2008 at 10:17 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:

> GTXY20 wrote:
>
> >
> > Hi tutors,
> >
> > I currently have a dictionary like the following:
> >
> > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
> > '3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
> > ['238', '238'], '7': ['220']}
> >
> > I am trying to create a dictionary that would list the current key and a
> > count of the iterations of values within the value list like so:
> >
> > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3:
> > { '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' :
> > 2}, '7': {'220' : 1}}
> >
>
> ?? Do you really want keys of '2' and 2? How can you have two keys '5'? I
> guess maybe you want
> {'1': {'220' : 3}, '2': {'220' : 1, 238 : 4}, '3': {'220' : 1, '238' : 1},
> '4': {220 : 2}, '5': {'220: 2, 238 : 1}, '6': {'238' : 2}, '7': {'220' : 1}}
>
>
> Now I am pretty sure that I need to loop through the first dictionary and
> > create a defaultdict from the values for each key in that dictionary but at
> > this point I am having difficulty coming up with the loop.
> >
> > I am looking for a satrting point or any suggestions.
> >
>
> Do you know how to turn
> ['220', '238', '238', '238', '238']
> into
> {'220' : 1, '238' : 4}
> ?
>
> If so, then put that code in a loop over the key, value pairs of the dict.
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested dictionary with defaultdict

2008-04-15 Thread Kepala Pening

count = lambda x: [{y: x.count(y)} for y in set(x)]
y = {}
for key, val in myDict.items():
y[key] = count(val)

print y

{'1': [{'220': 3}], '3': [{'238': 1}, {'220': 1}], '2': [{'238': 4}, {'220': 
1}], '5': [{'238': 1}, {'220': 2}], '4': [{'220': 2}], '7': [{'220': 1}], 
'6': [{'238': 2}]}



- Original Message -
From: GTXY20 <[EMAIL PROTECTED]>
To: tutor@python.org
Date: Tue, 15 Apr 2008 21:51:02 -0400
Subject: [Tutor] Nested dictionary with defaultdict

Hi tutors,

I currently have a dictionary like the following:

{'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'], '3': 
['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6': 
['238', '238'], '7': ['220']}

I am trying to create a dictionary that would list the current key and a 
count of the iterations of values within the value list like so:

{'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3: { 
'238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238' : 
2}, '7': {'220' : 1}}

Now I am pretty sure that I need to loop through the first dictionary and 
create a defaultdict from the values for each key in that dictionary but at 
this point I am having difficulty coming up with the loop.

I am looking for a satrting point or any suggestions.

Many thanks in advance.

GTXY20
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Nested dictionary with defaultdict

2008-04-15 Thread GTXY20
Thanks John and Kent for the guidance.

This following ends up working perfect for me - instead of print to the
console I will just write this to a text file. I will also wrap it in a
function.
from collections import defaultdict
d = {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
'3': ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
['238', '238'], '7': ['220']}

for f, b in d.items():
h = defaultdict(int)
for j in b:
h[j]+=1
for k,v in sorted (h.items()):
print ('%s, (%s:%s)' % (f, k, v))

M.


On Tue, Apr 15, 2008 at 10:19 PM, John Fouhy <[EMAIL PROTECTED]> wrote:

> On 16/04/2008, GTXY20 <[EMAIL PROTECTED]> wrote:
> > I currently have a dictionary like the following:
> >
> > {'1': ['220', '220', '220''], '2': ['220', '238', '238', '238', '238'],
> '3':
> > ['220', '238'], '4': ['220', '220'], '5': ['220', '220', '238'], '6':
> > ['238', '238'], '7': ['220']}
> >
> > I am trying to create a dictionary that would list the current key and a
> > count of the iterations of values within the value list like so:
> >
> > {'1': {'220' : 3}, '2': {'220' : 1}, 2: {238 : 4}, '3': {'220' : 1}, 3:
> {
> > '238' : 1}, '4': {220 : 2}, '5': {'220: 2}, '5': {238 : 1}, '6': {'238'
> :
> > 2}, '7': {'220' : 1}}
> [...]
> > I am looking for a satrting point or any suggestions.
>
> Can you write a function that will take a list and return a dictionary
> with the counts of elements in the list?
>
> i.e. something like:
>
> >>> def countValues(valueList):
> ...  # your code goes here
> ...
> >>> countValues(['220', '238', '238', '238', '238'])
> {'238': 4, '220': 1}
>
> P.S.  Your sample output is not a valid dictionary...
>
> --
> John.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread Marc Tompkins
On Tue, Apr 15, 2008 at 7:18 PM, <[EMAIL PROTECTED]> wrote:

> Recommendation: Find a very old version of Word (Word 95) to generate
> your RTF 'templates'. The older versions of Word generate much simpler
> RTF that is forward compatible.
>

Excellent advice!  Unfortunately, my case is a bit different...

All incoming files (from the transcribing company) will be coming in as RTF
and formatted properly - or at least they will if my instructions were
clearly understood.  In any case, future files are not my problem.  My
problem is transcriptions from the past year or so, maybe more - the
practice moved to a new software package, and it remains to be seen how much
history they want/need to load into the new EMR.  (It's not a primary-care
practice, so there's a lot of patient-base turnover.)

The files I have to deal with were generated by Word 2003, and now have been
converted to RTF by OpenOffice 2.4.  I just need to shove a (mostly) blank
page in at the beginning, with a slug of summary info, so that the import
utility can digest the file.
I've done it by hand on a few files now
 - open in Word*,
 - insert a section/page break at the top of the document
 - go to the second header and uncheck "Same as Previous"
 - go to the first header and delete it
 - close the header and enter the slug info
   (doctor is easy, as the files are separated into folders by doctor,
  but patient ID and date need to be determined for each file)
 - save
 - feed it to the import utility

*Although I have OpenOffice installed, and I used it - in Ubuntu - for the
batch conversion, I haven't yet checked to see whether this task is simpler
or more complicated in Writer.
** I just did.  Viva open source and all, but they've got a lng way to
catch up in ease of use - at least for this task...  

Since I have 10,000 or so files to do, the job screams for automation, and
Python is my favorite tool.  So hope springs eternal...

-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread Marc Tompkins
On Tue, Apr 15, 2008 at 7:10 PM, John Fouhy <[EMAIL PROTECTED]> wrote:

> Is this any help to you: http://pyrtf.sourceforge.net/
>

Not so much, because it only produces RTF - it doesn't help me pick apart
the stuff I've already got.
(It did cross my mind to try to create in pyRTF the same structure that I'm
trying to code by hand... but from my quick overview, pyRTF doesn't appear
to deal with "sections" in the same way Word does.  Maybe I'm missing
something, but I didn't see it.)

This, though: http://sourceforge.net/projects/pyrtflib/, parses the file and
extracts content from it; it just doesn't seem to pay much attention to the
non-content tags it picks through.  I think I'm going to have to figure out
a way to make the "agnostic" method work.

-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [Fwd: Re: Hoping to benefit from someone's experience...]

2008-04-15 Thread Luke Paireepinart

Sorry, forgot to cc the list.
--- Begin Message ---
On Tue, Apr 15, 2008 at 7:18 PM, <[EMAIL PROTECTED]> wrote:

> Recommendation: Find a very old version of Word (Word 95) to generate
> your RTF 'templates'. The older versions of Word generate much simpler
> RTF that is forward compatible.
>

Excellent advice!  Unfortunately, my case is a bit different...

All incoming files (from the transcribing company) will be coming in as RTF
and formatted properly - or at least they will if my instructions were
clearly understood.  In any case, future files are not my problem.  My
problem is transcriptions from the past year or so, maybe more - the
practice moved to a new software package, and it remains to be seen how much
history they want/need to load into the new EMR.  (It's not a primary-care
practice, so there's a lot of patient-base turnover.)

The files I have to deal with were generated by Word 2003, and now have been
converted to RTF by OpenOffice 2.4.  I just need to shove a (mostly) blank
page in at the beginning, with a slug of summary info, so that the import
utility can digest the file.
I've done it by hand on a few files now
 - open in Word*,
 - insert a section/page break at the top of the document
 - go to the second header and uncheck "Same as Previous"
 - go to the first header and delete it
 - close the header and enter the slug info
   (doctor is easy, as the files are separated into folders by doctor,
  but patient ID and date need to be determined for each file)
 - save
 - feed it to the import utility

*Although I have OpenOffice installed, and I used it - in Ubuntu - for the
batch conversion, I haven't yet checked to see whether this task is simpler
or more complicated in Writer.
** I just did.  Viva open source and all, but they've got a lng way to
catch up in ease of use - at least for this task...  

Since I have 10,000 or so files to do, the job screams for automation, and
Python is my favorite tool.  So hope springs eternal...

-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
--- End Message ---
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread Marc Tompkins
On Tue, Apr 15, 2008 at 8:50 PM, Luke Paireepinart <[EMAIL PROTECTED]>
wrote:

> Sorry, forgot to cc the list.
>
Actually, you cc'd the list with my previous post instead of your response
to it.  Here's what you sent me:

> I don't know if this is the best way, but given that other guy's
> suggestion about RTF,
> why not create a new document formatted how you want,
> then use ooconvert to throw all of your files into text files.
> Then you don't have to deal with parsing the original files, and you can
> use the data from the text files and then generate new RTFs?
> You can see how the result is... just make sure you don't overwrite your
> original RTFs!
> -Luke


I _have_ been thinking about this... but I don't think it's going to fly.
Apart from the header and footer (which would be a snap to re-create), the
reports include a good deal of formatting, without which they're nearly
impossible to comprehend.  (Bulleted lists, numbered lists, S.O.A.P.
quadrants, reviews of systems with the name of each system bolded for
emphasis...)  From a publishing or stylistic point of view, they're a
freaking nightmare, but this is medicine, not literature!

Furthermore, the formatting varies from document to document...  basically,
this would require reviewing each of the 10K documents to make sure it still
makes sense after its travels - and, almost as important, still resembles
the printed document sitting in a file cabinet somewhere.

I've been very impressed by how well OO saved the formatting during
conversion from .doc to .rtf... but I don't want to push my luck too far.

I'm sorry if it seems I'm just shooting everything down - it's just that I
had done a good bit of thinking about my problem before I wrote my original
question.

Moving away from the RTF horn of my dilemma, does anyone have any experience
writing OO macros?  Or know of any sites with more than ten lines of
documentation?  I'm studying ooconvert itself, but that's only getting me so
far.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hoping to benefit from someone's experience...

2008-04-15 Thread Alan Gauld

"Marc Tompkins" <[EMAIL PROTECTED]> wrote

> Moving away from the RTF horn of my dilemma, does anyone have any 
> experience
> writing OO macros?  Or know of any sites with more than ten lines of
> documentation?  I'm studying ooconvert itself, but that's only 
> getting me so
> far.

Have you considered driving Word instead of OOo?
That way you leave the documents in their original format
and make the mods using COM from Python.

Python and COM are not super friendly but they are not impossible
either. And if you can record some Macros in Word and save them
as functions you should be able to call those macros from a python
script that just orchestrates the macros.

Alternatively learn enough VBScript to do it all in Word itself

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor