Gribouillis 1,391 Programming Explorer Team Colleague

Add str(cnt).

By the way, this is better:

with open("foo.csv") as f: cnt = sum(1 for line in f)

because the file is properly closed.

Gribouillis 1,391 Programming Explorer Team Colleague

You can use

cnt = sum(1 for line in open("foo.csv"))
Gribouillis 1,391 Programming Explorer Team Colleague

Sorry I only have python-wxgtk2.8 in kubuntu :(

Gribouillis 1,391 Programming Explorer Team Colleague

The problem is that due to the assignment statement at line 34, dealer_num becomes a local variable in nowviewing(). It means that it is a different variable with the same name. The solution is to add the line global dealer_num at the beginning of nowviewing() to tell python that this is a global variable.

Later, you will learn to avoid the need for global statements like this.

Also, the recursive call to nowviewing() at the end of the function would be better written as a while loop, without recursion.

Gribouillis 1,391 Programming Explorer Team Colleague

os.chdir(os.getcwd())

This is a no-op :)

Gribouillis 1,391 Programming Explorer Team Colleague

I suggest the official python tutorial to start with.

Gribouillis 1,391 Programming Explorer Team Colleague

Regex's anyone?

I would use

r".*(?:\.py|\.txt)\Z(?ims)"

because glob uses fnmatch, which translates shell patterns into python regex, and this is how '.*' is translated:

>>> from fnmatch import translate
>>> translate('*.py')
'.*\\.py\\Z(?ms)'

I think it makes a difference if file names contain newline characters. The following works in my linux system, creating a file name containing newlines

>>> with open("foo\nbar.txt\n", "w") as ofh:
...  ofh.write('foobar')
... 
>>> 

your regex will list this file which does not end with .txt.

Hiroshe commented: good point! +7
Gribouillis 1,391 Programming Explorer Team Colleague

Hm, os.listdir() returns names, one probably needs

filenames = [os.path.join(directory, name) for name in os.listdir(directory) if name.endswith(('.py', '.txt'))]
Gribouillis 1,391 Programming Explorer Team Colleague

My father in law bought an asus which broke down rapidly. On the other hand, I had one which worked very well during almost 10 years. I bought 3 acer aspire laptops for 500/700 euros in the last 2 years, and they do their job. The first thing I do is erase windows 8 and install linux on them :)

Edit: for 10 years, add 1 or 2 battery replacements.

Gribouillis 1,391 Programming Explorer Team Colleague

Instead of

if ...
if ...
if ...
else ...

use

if ...
elif ...
elif ...
else ...

If you need to go to the next iteration of a while loop, you can use a

continue

statement.

Gribouillis 1,391 Programming Explorer Team Colleague

Of course, I said it is this code snippet: http://www.daniweb.com/software-development/python/code/374530/post-process-generated-values-with-a-decorator
Here is the contents of post_process.py

# python >= 2.6
from functools import update_wrapper

def post_process(*filters):
    """Decorator to post process a function's return value through a
    sequence of filters (functions with a single argument).

    Example:

        @post_process(f1, f2, f3)
        def f(*args, **kwd):
            ...
            return value

        then calling f(...) will actually return f3( f2( f1( f(...)))).

        This can also be used to convert a generator to a function
        returning a sequence type:

        @post_process(dict)
        def my_generator():
            ...
            yield key, value

    """

    def decorate(func):
        def wrapper(*args, **kwd):
            rv = func(*args, **kwd)
            for f in filters:
                rv = f(rv)
            return rv
        update_wrapper(wrapper, func)
        return wrapper
    return decorate
Gribouillis 1,391 Programming Explorer Team Colleague

Sorry I meant

@post_process(list)
def gather(xml_doc, paths):
    for p in paths:
        node = xml_doc
        for word in p:
            node = node[word]
        yield node

getitem() exists, but it is in module operator. You must also import post_process() from another file. For example, store it in a module post_process.py and write

from post_process import post_process
Gribouillis 1,391 Programming Explorer Team Colleague

In this case, the decorator transform a function which generate values into a function which returns a list of these values. Without the decorator, I would write

def gather(xml_doc, paths):
    result = []
    for p in paths:
        node = xml_doc
        for word in p:
            node = getitem(node, word)
        result.append(node)
    return result

This way to compose the resulting list is tedious, and this is a recurrent pattern. That's why I use the decorator.

Gribouillis 1,391 Programming Explorer Team Colleague

How does this compare to using a Python function such as filter.

Can you be more specific ? The role of filter() is to select a subsequence in a sequence. It is a different problem.

Gribouillis 1,391 Programming Explorer Team Colleague

You can define a function to do the same easily

@post_process(list)
def gather(xml_doc, paths):
    for p in paths:
        node = xml_doc
        for word in p:
            node = getitem(node, word)
        yield node


a = gather(xml_doc, (('meeting', '@id'), ('meeting', '@venue')))

post_process is defined in this code snippet (very useful bit).

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps play with the .next_siblings and .sibling attributes of the title tag.

Gribouillis 1,391 Programming Explorer Team Colleague

This is a typical use case for generators and tools for iterables. Instead of writing to a file, use a generator

import os
import xml.etree.ElementTree as ET
from itertools import ifilterfalse

def generate_lines():
    tree = ET.parse("Logfile.xml")
    root = tree.getroot()
    for element in root.iter('Path'):
        file_name = os.path.basename(element.text)
        #.exe just an example that you can have more values
        if not file_name.endswith(('.exe', '.fmt', 'sys', 'tmp')):
            #print 'copy %windir%\system32\', file_name, '%1%'
            yield ('copy %windiw&\system32\{} %1%\n').format(
                os.path.basename(element.text))

Now, elimination of duplicates is a standard pattern. There is a generic solution at the end of itertools' module documentation

def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

We're ready to write the output file

with open('my_file.txt', 'w') as f_out:
    lines = unique_everseen(generate_lines())
    f_out.writelines(lines)
Gribouillis 1,391 Programming Explorer Team Colleague

You only need to keep the set of already seen PC Numbers

seen = set()
# ...

for row in ...:
    n = row['PC Number'].strip()
    mode = 'ab+' if n in seen else 'wb'
    with open('pc_Numbers_' + n +'.csv', mode) as fid:
        cf2 = csv.DictWriter(fid, new_field_names)
        if n not in seen:
            cf2.writeheader()
            seen.add(n)
        cf2.writerow(row)

However, it may be inefficient to open a file for every row. You could store a dictionary of opened files and dictwriters, with the pc numbers as keys.

Gribouillis 1,391 Programming Explorer Team Colleague

Use os.path.exists() or os.path.isfile() depending on what you want to do.

Gribouillis 1,391 Programming Explorer Team Colleague

Use one of vegaseat's tkinter examples. You can adapt the example by reading the file from your disk instead of the internet.

Gribouillis 1,391 Programming Explorer Team Colleague

I'm using kubuntu, but it should work in debian: make sure you have the development packages for python (python-dev and libpython-dev):

sudo aptitude search python-dev
# then may be
sudo aptitude install python-dev
sudo aptitude install libpython-dev
sudo aptitude install python-setuptools
sudo aptitude install python-pip

Then

sudo pip install pycrypto

should work.

There are windows binaries here but there are reported to be incomplete here. Make sure you visit this page.

Gribouillis 1,391 Programming Explorer Team Colleague

You can improve the program by using the standard module cmd which purpose is to write interactive command line interpreters. I wrote an enhanced class of cmd.Cmd in this code snippet. It makes it very easy to write an interpreter: copy the class ExampleCmd at the end of the file and add methods do_ls() do_add() do_open() etc with arguments and docstring. The help command is automatically provided.

Gribouillis 1,391 Programming Explorer Team Colleague

You're welcome.
Why not click on the Mark Question Solved button ?

Gribouillis 1,391 Programming Explorer Team Colleague

I used this

lst = re.findall(r"{\s[^}]*0x01\s}",str1)

and it worked.

Gribouillis 1,391 Programming Explorer Team Colleague

Use re.findall()

Gribouillis 1,391 Programming Explorer Team Colleague

I see 2 solutions

  1. You wait until python 3.4 is the packaged python 3 version in your linux distro (this is currently python 3.3.2+ in my kubuntu).
  2. You download the source tarball and you compile it yourself, using something like 'configure' and 'make altinstall'. There may be dependencies for the huge python standard library.

Most probably, you don't need python 3.4. Use the last python 3.3 for some time.

Gribouillis 1,391 Programming Explorer Team Colleague

Try to use this command class instead of subprocess.call()

com = Command(scriptPath).run()
print(com.output)
print(com.error)
Gribouillis 1,391 Programming Explorer Team Colleague

I don't know, it seems that you are copying and pasting code without understanding it. It can't work this way. Your code is not properly indented with 4 spaces. I gave you the link to Tim Peter's reindent script, why don't you use it to clean your program, and configure your editor to indent with 4 spaces ? Also your Tkinter program doesn't need 3 calls to mainloop(). Normally only one call is needed. It means that you don't understand what mainloop does. etc. I think you want to go too fast, but you should read a python tutorial such as dive into python 3.

Gribouillis 1,391 Programming Explorer Team Colleague

You can iterate on sorted keys:

for channel_key in sorted(channels):
    ...

The other thing you can do is use

channels = OrderedDict()

instead of channels = {}. In py 2.6, ordereddict is here. Then the dict should be traversed in the insertion order (while sorted() yields alphabetic order, which could be different)

mark103 commented: Very good thank you +0
Gribouillis 1,391 Programming Explorer Team Colleague

According to
mktime takes struct_time in local time as per
"Use the following functions to convert between time representations:" section of the page

As Opsive wrote 10 posts 5 years ago, we guess that (s)he is not waiting for an answer today. Please don't revive old threads. Start your own thread instead.

Gribouillis 1,391 Programming Explorer Team Colleague

Again we don't know precisely the information that you need. Apparently, your numbers are ordered (but the last number), so I suppose that you treat the first 5 numbers as a set rather than a list. Here is a piece of code which computes a score function for each line by comparing the line to the target line. The score is a pair of numbers (n, m), where n
is the number of correct guesses among the 5 first numbers, and m is 0 or 1 depending on
the last number (1 if it matches the target, 0 otherwise). I'm sure you can use this score function in your code.

data = [line.split() for line in """
13 27 34 41 47 - 49
22 24 45 46 51 - 15
10 14 22 23 42 - 13
01 04 17 31 52 - 38
12 23 40 47 57 - 04
""".strip().splitlines()]

target = "07 13 14 23 45 - 07".split()

print(data)
print(target)

def score(a, b):
    return (len(set(a[:5]) & set(b[:5])), 1 if (a[-1] == b[-1]) else 0)

print()
for a in data:
    print(a, score(a, target))

""" my output -->
[['13', '27', '34', '41', '47', '-', '49'], ['22', '24', '45', '46', '51', '-', '15'], ['10', '14', '22', '23', '42', '-', '13'], ['01', '04', '17', '31', '52', '-', '38'], ['12', '23', '40', '47', '57', '-', '04']]
['07', '13', '14', '23', '45', '-', '07']

['13', '27', '34', '41', '47', '-', '49'] (1, 0)
['22', '24', '45', '46', '51', '-', '15'] …
Gribouillis 1,391 Programming Explorer Team Colleague

I want to output something is like: v0 v1 v2 v3 v4

Simply don't print the whole dict every time an item is inserted, so for example

D = {}

for i in range(5):
    D[i] = "v%d" % i
    print D[D_key],

or

D = {}

for i in range(5):
    D[i] = "v%d" % i

for D_key in D:
    print D[D_key],
Gribouillis 1,391 Programming Explorer Team Colleague

Apparently it comes from tutors at python.org 7 years ago. Read this mail.

Gribouillis 1,391 Programming Explorer Team Colleague

So I don't understand what you did.

Your initial question is ambiguous. You're describing what you want to do, instead of describing the information you need.

It would be easier if you tell us exactly what you want from the lists

x0 x1 x2 x3 x4 - x5
y0 y1 y2 y3 y4 - y5

For example "I want the list of items in x0 x1 x2 x3 x4 which belong to y0 y1 y2 y3 y4". That would be

a = ['06', '15', '26', '34', '36', '-', '16']
b = ['16', '24', '34', '30', '43', '-', '20']

result = list(set(b[:5])& set(a[:5]))

or "I want the list of integers i for which a[i] and b[i] are equal". That would be

m = min(len(a), len(b))
indexes = [i for i in range(m) if a[i] == b[i]]
Gribouillis 1,391 Programming Explorer Team Colleague

To make it short, I think you are doing this with dict channels

D = {}

for i in range(5):
    D[i] = "v%d" % i
    for D_key in D:
        print D[D_key],

""" my output -->
v0 v0 v1 v0 v1 v2 v0 v1 v2 v3 v0 v1 v2 v3 v4
"""

Isn't this obviously wrong ?

Gribouillis 1,391 Programming Explorer Team Colleague

Yes, you must learn to manipulate python's container data types: lists, sets, dicts. You can do many things with your data

a = ['06', '15', '26', '34', '36', '-', '16']
b = ['16', '24', '30', '34', '43', '-', '20']

xa = a[:-2] # take all elements but the last 2 ones
xb = b[:-2]

nl = '\n'
print(xa, xb, sep = nl)
"""
['06', '15', '26', '34', '36']
['16', '24', '30', '34', '43']
"""

ya = set(xa) # build unordered sets instead of lists
yb = set(xb)
print(ya, yb, sep = nl)
"""
{'15', '26', '34', '06', '36'}
{'16', '43', '34', '24', '30'}
"""
print(ya & yb)
print(ya - yb)
print(yb - ya)
print(ya == yb)
"""
{'34'} # elements in ya and yb
{'15', '26', '36', '06'} # items in ya but not in yb
{'16', '30', '43', '24'} # items in yb but not in ya 
False # the 2 sets are different
"""
lasta = a[-1] # take the last numbers
lastb = b[-1]
print(lasta, lastb, lasta == lastb, sep = nl)
"""
16
20
False
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Do you know what a python list is ? Read this example about reading a data file line by line and manipulate its content.

Gribouillis 1,391 Programming Explorer Team Colleague

A hint:

>>> line = '14 18 35 47 54 - 57\n'
>>> line.split()
['14', '18', '35', '47', '54', '-', '57']
Gribouillis 1,391 Programming Explorer Team Colleague

Here is the complete code

from tkinter import*
import sys, random, tkinter
ticket_price = 2
i=0
total = 0
def calculatetotals():
    valid = set('12345')
    ticket_entry = tik.get()
    if ticket_entry not in valid:
        print('We permit values in {}.'.format(valid))
        label4 = Label(aApp,text = 'We permit values in 1, 2, 3, 4 or 5!',fg = 'blue').grid(row=7,column=1)
    else:
        label4 = Label(aApp,text = '                                                                        ',fg = 'blue').grid(row=7,column=1)
        mytik=int(ticket_entry)
        total = mytik*ticket_price
        Label(aApp,text= "You purchased:$%.2f \n" %  total).grid(row=7,column=1)
        Label(aApp,text= "\nNumber Of Tckets: %.f\n" % mytik).grid(row=6,column=1)
        Button(aApp,text="Click Here To Draw Your Tickets!",fg='blue',bg='white'\
               ,command = nextx).grid(row=8,column=1)
aApp=Tk()
aApp.geometry('580x170+200+270')
aApp.title("LOTTO")
tik=StringVar()
label1 = Label(aApp,text = "Welcome To Lotto.",fg = 'blue')
label1.grid(row=0,column=2)
label2=Label(aApp,text="Tickets Are ${:.2f} Each.".format(ticket_price),fg='red')
label2.grid(row=1,column=1)
label3=Label(aApp,text="How Many Would You Like?",fg='black')
label3.grid(row=2,column=1)
mytik = Entry(aApp,textvariable=tik)
mytik.grid(row=2,column=2)
button1=Button(aApp,text="Your Purchse\nClick Here",fg='blue'\
               ,command=calculatetotals)
button1.grid(row=6,column=1)
def nextx():
    Button(aApp,text="Click Here to see the new winning number.",fg='lightgreen',bg='black'\
           ,command = nextz).grid(row=8,column=1)
    ticket_entry = tik.get()
    #######################################
    # outputs to Window and File("C:\output.txt","a")
    #######################################
    i = 0
    while i < int(ticket_entry):
        L = list(range(1,60))
        random.shuffle(L)
        g = L[:5]
        g.sort()
        f = L[5:6]
        drawing = '  '.join( ['  '.join(zstr(G)  for  G  in g),' -',zstr(f[0])])
        label5=tkinter.Label(app,text = drawing  ).pack(padx=1,pady=2)
        text_file = open("C:\output.txt","a")
        text_file.write('\n')
        text_file.write(drawing)
        text_file.close()
        i+=1
       #########################################
       # Finnished output to window and File
        #########################################
app=tkinter.Tk()
app.geometry('600x400+75+75')
app.title(string="     NUMBERS      ")
Button(app, text="Quit", command=app.quit).pack()
def  nextz():
    Button(aApp,text='Push   again to  <Quit> : To see if you match Push <Compare> In The New Winning Number Window, '\
           ,fg='yellow',bg='black',command = quit).grid(row=8,column=1)
    L = list(range(1,60))
    random.shuffle(L)
    g = L[:5]
    g.sort()
    f = L[5:6]
    drawing = '  '.join( [' - '.join(str(G)  for  G  in g),' …
Gribouillis 1,391 Programming Explorer Team Colleague

As I said above, use

        drawing = '  '.join( ['  '.join(zstr(G)  for  G  in g),' -',zstr(f[0])])

and the above function zstr().

Gribouillis 1,391 Programming Explorer Team Colleague

At line 49 (in my version), replace str() with zstr() and define

def zstr(ob, width = 2):
    return '{x:0>{width}s}'.format(x = str(ob), width = width)
Gribouillis 1,391 Programming Explorer Team Colleague

There is also a solution with the re module

import re

def cap(match):
    return match.group(0).capitalize()

with open('c:\FLOUpper.txt', 'r') as infile, open('c:\FLOLower.txt', 'w') as outfile:
    s = infile.read()
    s = re.sub(r'\b[a-zA-Z]\w*', cap, s)
    outfile.write(s)
Shaji_1 commented: Utilized this solution and it worked like a charm. Thank you! +0
Gribouillis 1,391 Programming Explorer Team Colleague

You can start by writing pseudo-code to describe the different things that your program must do

# print a message saying that the following table
# displays temperatures in celsius and their
# conversion to farenheit.

Your-code-here

# set the celsius temperature C to zero

Your-code-here

# while the celsius temperature C is <= 20 degrees

Your-code-here

    # compute the farenheit temperature F

    Your-code-here

    # print the 2 temperatures C and F

    Your-code-here

    # increase the temperature C by one degree

    Your-code-here
Gribouillis 1,391 Programming Explorer Team Colleague

Here is the code, reindented with tim peter's reindent (not sure it would work without python 2)

from tkinter import*
import sys, random, tkinter
ticket_price = 2
i=0
total = 0
def calculatetotals():
    valid = set('12345')
    ticket_entry = tik.get()
    if ticket_entry not in valid:
        print('We permit values in {}.'.format(valid))
        label4 = Label(aApp,text = 'We permit values in 1, 2, 3, 4 or 5!',fg = 'blue').grid(row=7,column=1)
    else:
        label4 = Label(aApp,text = '                                                                        ',fg = 'blue').grid(row=7,column=1)
        mytik=int(ticket_entry)
        total = mytik*ticket_price
        Label(aApp,text= "You purchased:$%.2f \n" %  total).grid(row=7,column=1)
        Label(aApp,text= "\nNumber Of Tckets: %.f\n" % mytik).grid(row=6,column=1)
        Button(aApp,text="Click Here To Draw Your Tickets!",fg='blue',bg='white'\
               ,command = nextx).grid(row=8,column=1)
aApp=Tk()
aApp.geometry('580x170+200+270')
aApp.title("LOTTO")
tik=StringVar()
label1 = Label(aApp,text = "Welcome To Lotto.",fg = 'blue')
label1.grid(row=0,column=2)
label2=Label(aApp,text="Tickets Are ${:.2f} Each.".format(ticket_price),fg='red')
label2.grid(row=1,column=1)
label3=Label(aApp,text="How Many Would You Like?",fg='black')
label3.grid(row=2,column=1)
mytik = Entry(aApp,textvariable=tik)
mytik.grid(row=2,column=2)
button1=Button(aApp,text="Your Purchse\nClick Here",fg='blue'\
               ,command=calculatetotals)
button1.grid(row=6,column=1)
def nextx():
    Button(aApp,text="Click Here to see the new winning number.",fg='lightgreen',bg='black'\
           ,command = nextz).grid(row=8,column=1)
    ticket_entry = tik.get()
    #######################################
    # outputs to Window and File("C:\output.txt","a")
    #######################################
    i = 0
    while i < int(ticket_entry):
        L = list(range(1,60))
        random.shuffle(L)
        g = L[:5]
        g.sort()
        f = L[5:6]
        drawing = '  '.join( ['  '.join(str(G)  for  G  in g),' -',str(f[0])])
        label5=tkinter.Label(app,text = drawing  ).pack(padx=1,pady=2)
        text_file = open("C:\output.txt","a")
        text_file.write('\n')
        text_file.write(drawing)
        text_file.close()
        i+=1
       #########################################
       # Finnished output to window and File
        #########################################
app=tkinter.Tk()
app.geometry('600x400+75+75')
app.title(string="     NUMBERS      ")
Button(app, text="Quit", command=app.quit).pack()
def  nextz():
    Button(aApp,text='Push   again to  <Quit> : To see if you match Push <Compare> In The New Winning Number Window, '\
           ,fg='yellow',bg='black',command = quit).grid(row=8,column=1)
    L = list(range(1,60))
    random.shuffle(L)
    g = L[:5]
    g.sort() …
Gribouillis 1,391 Programming Explorer Team Colleague

Is this blue enough ?

        self.btnClear = Button(
            self.frame, text="Clear Test", relief = FLAT,
            bg = "blue",highlightbackground="blue", fg="white")
Gribouillis 1,391 Programming Explorer Team Colleague

It looks very much like homework. Start with a program to print the letters of each word in alphabetic order.

Gribouillis 1,391 Programming Explorer Team Colleague

Add print('Current item is:', repr(item)) between lines 3 and 4.

Gribouillis 1,391 Programming Explorer Team Colleague

Yes, but you will write in python 3 in the future if you don't do it yet, so why not write (almost) compatible code right now ? There are good reasons for this

  • Python 3 is better than python 2 (more consistent and homogeneous)
  • It is not more difficult to write python 3 code
  • Your code may run out of the box the day you decide it is time to use python 3, so less work for tomorrow
Gribouillis 1,391 Programming Explorer Team Colleague

Use u'à1' and u'é1' or even better

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)

Currently, I even use

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from future import standard_library
from future.builtins import *

in python 2.7, where future is this module.

Gribouillis 1,391 Programming Explorer Team Colleague

What about pip and cython ? do they work now ?