woooee 814 Nearly a Posting Maven
longestSentence = max((listOfWords for listOfWords in listOfSents if any(lt == word.lower() for word in listOfWords)), key = len)
    #get longest sentence -list format with every word of sentence being an actual element-
 
    longestSent=[longestSentence]
 
    for word in longestSent:#convert the list longestSentence to an actual string

Break down the list comprehension into something readable. Perhaps splitting on the sentence break, ". ", and sending each sentence to a function which checks for the trigger word, and then returns the length of the sentence if the trigger is found, or zero if not found.

woooee 814 Nearly a Posting Maven

Divide by 3, multiply the result by 3, and compare to the original number, assuming that you are using integers only.

woooee 814 Nearly a Posting Maven

If you are looking for the same English word in both files, use one set for each file and then you can get the difference or intersection of the sets. http://en.wikibooks.org/wiki/Python_Programming/Sets To read two files, you open the first file, process it (add to the set or whatever), and then close it. Then open the second file and repeat the process http://diveintopython.org/file_handling/file_objects.html

TrustyTony commented: Good guidance without ready answer +2
woooee 814 Nearly a Posting Maven

Store the "short" line and blank it after writing. If there isn't a short line, the store variable will be empty.

in_file = open('myhugetextfile.txt')
out_file = open('mycleaneduptextfile.txt','w')
 
#go through the file line by line
repaired_line = "" 
for line in in_file:
 
     #split on ;; and check if the length is less than 11 entries long
     #if length is less than 11, it means the line has an unnecessary newline in it
 
     if len(line.split(';;')) < 11:
          #strip the unneeded newline char off the end of the line
          line = line.strip('\n')
 
          #  store this value
          repaired_line = line
 
      else:
         out_file.write(repaired_line + line)
         
         ## blank repaired_line after every write
         repaired_line = ""
woooee 814 Nearly a Posting Maven

The easiest way is to use a class and define the dictionary as self.some_name so you can access it inside or outside the class. A simple example:

class TestClass:

    def __init__(self):
        self.test_name = "test name from class"

    def print_object_variable(self):
        print "variable within class -->", self.test_name

x = TestClass()
print "outside class -->", x.test_name
x.print_object_variable()
woooee 814 Nearly a Posting Maven

If I understand the question, you want to print file dates that have not already been printed so you have to use some sort of container, a list for example, which contains the dates already printed, and print only if the date has not already been used.

woooee 814 Nearly a Posting Maven

It sounds like either the screensaver or the wxPython time out (for certain types of widgets). I don't use timeout so am not familiar with it other than seeing it in the docs. Your program should allow the user a certain amount of time to choose a file, and if they haven't made a decision in say 2 or 3 minutes, exit. And you should print picsFolder for your own information to see if it contains the complete path or just the file name. Also, it is better IMHO to use the complete path instead of os.chdir() as it can get confusing as to which directory you are actually in. Finally, it is bad form to use the same name for a variable and a class, i.e.
picsFolder = self.picsFolder.GetValue()

picsFolder = ClassInstance()  ## variable is a class instance
##
picsFolder = self.picsFolder.GetValue()  ## picsFolder is now a variable (the class instance is gone) 
##
## In Python CamelCase is used for class instances and 
## lower_case is used for variables and we don't get mixed up
## The style guide is here, http://www.python.org/dev/peps/pep-0008
## if you are interested
woooee 814 Nearly a Posting Maven

I looked through all 10 of your previous posts and you haven't produced one line of code. It's about time you did or find another site to get free programming.

woooee 814 Nearly a Posting Maven

I would try render first, but I have never tried it. From the docs at http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qgraphicsview.html

QGraphicsView.render (self, QPainter, QRectF target = QRectF(), QRect source = QRect(), Qt.AspectRatioMode mode = Qt.KeepAspectRatio)

Renders the source rect, which is in view coordinates, from the scene into target, which is in paint device coordinates, using painter. This function is useful for capturing the contents of the view onto a paint device, such as a QImage (e.g., to take a screenshot), or for printing to QPrinter.

You could also try the PyQt Forum

woooee 814 Nearly a Posting Maven

Of course. I'm so old, I remember when everyone used land lines and dad didn't call you on your phone; he used his unique whistle to find you or call you in from outside (unless the street lights were on, in which case you'd better be in already).

woooee 814 Nearly a Posting Maven

It's in the repository https://admin.fedoraproject.org/pkgdb/acls/name/qscintilla?_csrf_token=ad09f71cc75d6c163204002663217b089dd6945c so you can install it like any other software.

I get an error message.........(bash: qmake command not found)

On my Slackware machine, qmake is in /usr/lib/qt which is not in the path, so you would have to call it with
/usr/lib/qt/qmake ...

woooee 814 Nearly a Posting Maven

You come from a time when shorts were short(s) and knickers were golf attire.

EDIT:

//yay your old

Is it just me, or has spelling become worse during the spell-checker era?

woooee 814 Nearly a Posting Maven

QImage has a save function. See "Reading and Writing Image Files" here

woooee 814 Nearly a Posting Maven

Split on the period. Note that the following doesn't make sense/requires an example.

Also, if a sentence is long, does not end in the same paragraph, it should be printed as a whole too

woooee 814 Nearly a Posting Maven

You can use the code you have with a range from total rows to zero and a step of -1, or a counter for the number of stars to print.

total_rows = 5

num_stars = total_rows
for row in range (total_rows): 
    print '*' * num_stars
    num_stars -= 1
woooee 814 Nearly a Posting Maven

If I understand correctly, you would modify the RemovePunc() function to receive an individual record from the file, and then execute the rest of the code as is

line = RemovePunc(file_record)
line_stop_words = RemoveStopWords(line)
line_stop_words = StemWords(line_stop_words)
index = Indexing(line_stop_words)
OutputIndex(index)

See here http://www.greenteapress.com/thinkpython/html/book010.html#wordlist

woooee 814 Nearly a Posting Maven

File "C:\Python26\lib\site-packages\pymysql-0.2-py2.6.egg\pymysql\connections.py"

We'll eliminate the easy stuff first. Do you have MySQL installed and is the MySQL server running?

woooee 814 Nearly a Posting Maven

Take a look at the first paragraph of the first hit here. You can just comment that line and keep the default cursor.

woooee 814 Nearly a Posting Maven

The error is:
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

There isn't any "+" sign in the code you posted. How about posting the entire error message including the offending line of code,

woooee 814 Nearly a Posting Maven

Python usually has ways of replacing a bunch of if/elif/else statements.

for field in infos:
        if field.startswith('AC'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('ID'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('FA'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('OS'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('SF'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('BS'):
            f_out.write('%s\t' % field[3:])
        elif field.startswith('GE'):
            f_out.write('%s\t\n' % field[3:])

    ## ---------  replace with  ----------
    for field in infos:
        test_2 = field[0:2]
        if test_2 in ["AC", "ID", "FA", "OS", "SF", "BS", "GE"]:  
            f_out.write('%s\t\n' % field[3:])
woooee 814 Nearly a Posting Maven

In pictures of friends and relatives, they are always sitting down.

woooee 814 Nearly a Posting Maven

I want make relation with gsm modem.

We don't know what this means. If you want to communicate via a serial port, check out USPP and PySerial, but however the signal enters your computer, you will have to have an interface to the port.

woooee 814 Nearly a Posting Maven

I need to read in the first 2 columns until line 12960. I then need to write the 12960 lines of 2 columns to a file.

You can use enumerate to count the records as it appears that a file is shorter than you think or there are blank records.

import os, glob 
def process_file(fname, f_output):
    print "processing", fname
    f_input = open(fname, "r")
								
    for num, rec in enumerate(f_input):
        if (num > 5) and (num < 12961):
            firstdata, seconddata, thirddata = rec.split(' ')[:3]
            f_output.write('%s, %s, %s,\n' % (firstdata, seconddata, thirddata))

    f_input.close()


f_output= open('output.txt','w')
path = './' 
for dir, subdir, files in os.walk(path):
    for fname in files:
        if glob.fnmatch.fnmatch(file,"xxx*.txt"): 
            process_file(os.path.join(dir, fname), f_output)
f_output.close()
woooee 814 Nearly a Posting Maven

This should be:

## changed to s[0] and d1, di.keys() is not necessary
        if s[0] not in d1:
woooee 814 Nearly a Posting Maven

Try
greeting = Text(Point(300, 250), "Hello," + player + "and good night")
Otherwise:
print_str = "Hello," + player + "and good night"
greeting = Text(Point(300, 250), print_str)

woooee 814 Nearly a Posting Maven

Use a function and pass the file name to it. Some pseudo-code:

def mapper_dict(fname, word_dict):
    ## assumes word is first element after split()
    fp = open(fname, "r")
    for rec in fp:
        substrs = rec.split()
        word = substrs[0]
        if word not in word_dict:
            word_dict[word] = 0
        word_dict[word] += 1
    return word_dict

word_dict = {}
for fname in ["/a/b/abc", "/d/e/def", "/g/h/ghi"]:
    word_dict = mapper_dict(fname, word_dict)
woooee 814 Nearly a Posting Maven

Personal preference here is to use a dictionary, with the key being the word, pointing to the number. Convert the first list to a dictionary, loop through the second list and if the word is found in the dictionary, add to the number http://www.greenteapress.com/thinkpython/html/book012.html#toc120 Post back with any code you are having coding problems with for additional help.

woooee 814 Nearly a Posting Maven

If you are a female geek no need to read this as the odds greatly favor you no matter what you do.

"scientists at the University of Leeds in Great Britain have determined that if you want to meet the right man, the optimum amount of flesh to flash is 40%. Less than that and you might appear too dowdy to catch his eye, any more and you’re more likely to attract a stalker than a soul mate. Psychologist Colin Hendrie had his four female assistants perform demanding “undercover” surveillance in Leeds’ nightclubs, recording how women were dressed and how often they were approached on concealed dictaphones. But it wasn’t just the women who were being judged. Hendie’s results also showed that the most successful approaches came from men who were neither too thin nor too fat and at least a head taller than their target. It also revealed that 30% of clubbers left as couples, though only 20% arrived so" (Daily Mail).

woooee 814 Nearly a Posting Maven

You would have to name it yourself via a class variable (shared by all instances of the class)

class TestClass(object):
    class_name = "TestClass"  ##  class variable
    def __init__(self):
        print "class instantiated"
 
print TestClass.class_name
ins = TestClass()
print TestClass.class_name
woooee 814 Nearly a Posting Maven

I don't see a problem on my machine using this simple example so it probably has nothing to do with time.sleep(). The queue perhaps?

import time
from multiprocessing import Process

class TestClass():
   def test_f(self, name):
      ctr = 0
      while True:
         ctr += 1
         print name, ctr
         time.sleep(1.0)
         
if __name__ == '__main__':
    CT=TestClass()
    p = Process(target=CT.test_f, args=('P1',))
    p.start()

    time.sleep(0.5)
    CT2=TestClass()
    p2 = Process(target=CT2.test_f, args=('  P2',))
    p2.start()

    ## sleep for 5 seconds and terminate
    time.sleep(5.0)
    p.terminate()

    print "\n program is still running"
    time.sleep(2.0)
    p2.terminate()
woooee 814 Nearly a Posting Maven

You can use the id also since you only want a name that is unique. Perhaps a dictionary with name/id --> class + args as well.

class TestClass(object):
    def __init__(self):
        print "class instantiated"
 
ins = TestClass()
unique_name = str(id(ins))
print unique_name
woooee 814 Nearly a Posting Maven

It is simple to use EasyGUI to get the data instead of keying in the entire file path, elevation, and pointbuff. Also, making one pass through the input file list and converting to floats will save doing that every time you access each record. An example follows with some sample code to print elevation differences that exceed the elevation input.

def convert_arg(arg_in):
    """ return a float if arg_in will convert, otherwise return zero
    """
    try:
        ret_arg = float(arg_in)
        return ret_arg
    except:  ## will catch anything, like "" that will not convert
        return 0


def get_file_name(dir_in = ""):
    """ example of choosing a file and entering data via EasyGUI
        http://easygui.sourceforge.net/
    """
    import easygui
    file_name_and_path = easygui.fileopenbox( \
                     "Double Click", "Choose your file", "/home/", "*")

    title = "pointbuff and elevation"
    msg = "Enter Now"
    field_names = ["Point Buff","Elevation"]
    field_values = []   ## start with no default values
    field_values = easygui.multenterbox(msg, title, field_names, field_values )

    # make sure that none of the fields was left blank
    while 1:
         if type(field_values) == None:
            field_values = [ -1, -1 ]
	    break
         errmsg = ""
         for x in range(len(field_names)):
            if field_values[x].strip() == "":
               errmsg = errmsg + ('"%s" is a required field.\n\n' % field_names[x])
         if errmsg == "": 
            break # no problems found
         field_values = easygui.multenterbox(errmsg, title, field_names, field_values)
    return file_name_and_path, field_values[0], field_values[1]


def read_file(filename):
    """ read the file, convert {1]. [2]. and [3] to floats and return
        the new list
    """
    converted_list = []
##    read1 = csv.reader(open(filename, 'rb'))
    read1 …
woooee 814 Nearly a Posting Maven

I essentially need to compare each Item in a list to every other item in the list.

Generally speaking, to compare you start with the first item in the list and compare to item #2, #3, etc. Then the same for the second item through n-1, as there is nothing to compare the last item to. A simple example to illustrate:

test_list = ["abc", "def", "abf", "abc", "abf", "xyz" ]

stop_y = len(test_list)
stop_x = stop_y -1
for x in range(0, stop_x):   ## stop at end-1
    ##  start at the next element and go through the end
    for y in range(x+1, stop_y):
        if test_list[x] == test_list[y]:
            print "2 are equal", test_list[x], x

Note that this brute force method can take some time with a large file (60,000 recs = 59,999 passes through the [smaller each time] list). A faster way is to use a set or dictionary indexed on the key element(s).

You should use a function instead of all of this code doing the same thing.

x2 = test[1]
        if x2 == "":
            x2 = 0
        else:
            x2 = float(x2)
        y2 = test[2]
        if y2 == "":
            y2 = 0
        else:
            y2= float(y2)
 
        elev2 = test[3]
        if elev2 == "":
            elev2 = 0
        else:
            elev2 = float(elev2)
##
##---------- use instead
def convert_arg(arg_in):
    """ return a float if arg_in will convert, otherwise return zero
    """
    try:
        ret_arg = float(arg_in)
        return ret_arg
    except:  ## will catch anything, like "" that will not convert
        return 0

x2 = …
woooee 814 Nearly a Posting Maven
L = 10 - len(answer)
list.append(answer + ' ' * L)

You can do this if you want but remember that Python has most things built in so you can also use: (look up string formatting)

print "%10s  %10s" % (car, answer)
##
## and your original code should read
print_list = [answer]
for x in range(10-len(answer):
    print_list.append(" ")
##
## which could also be done via
answer += " "*(10-len(answer)
woooee 814 Nearly a Posting Maven

That comes from the OS and depends on what "graphic card details" means. If you just want to know what type of graphics card, use subprocess to run lspci and pipe the output to a file. You can then read the file and search for "graphic".

woooee 814 Nearly a Posting Maven

What's the Python function/method/whatever to destroy an object?

Most of the tutorials for qt3 (if that is what you are using), use sys.exit().

import sys
import qt


class MyWidget(qt.QVBox):
    def __init__(self, parent=None, name=None):
        qt.QVBox.__init__(self, parent, name)

        quit = qt.QPushButton("Quit", self, "quit")
        quit.setFont(qt.QFont("Times", 18, qt.QFont.Bold))

        self.connect(quit, qt.SIGNAL("clicked()"), qt.qApp, qt.SLOT("quit()"))

        lcd = qt.QLCDNumber(2, self, "lcd")

        slider = qt.QSlider(qt.Qt.Horizontal, self, "slider")
        slider.setRange(0, 99)
        slider.setValue(0)

        self.connect(slider, qt.SIGNAL("valueChanged(int)"), lcd, qt.SLOT("display(int)"))


a = qt.QApplication(sys.argv)

w = MyWidget()
a.setMainWidget(w)
w.show()
sys.exit(a.exec_loop())

To destroy the object, assign something else to the variable.
(in pseudocode)
MW = MainWindow()
qApp.connect(qApp, SIGNAL(lastWindowClosed()), qApp, SLOT(quit()))
MW = ""

If you can supply a simple example of what you want to do it would help as you may want to use setModal or closeEvent.

woooee 814 Nearly a Posting Maven

You should be able to read the 100 bytes, split and write. The following code uses 25 bytes and splits from 10 through 20 (11 bytes) for simplicity.

alpha = "abcdefghijklmnopqrstuvwxy"
print alpha
print alpha[9:20]
woooee 814 Nearly a Posting Maven

Write a PYTHON function that takes the time as three integer arguments (for hours, minutes, and seconds)

You are supposed to create a function, not a class, that takes three arguments/parameters. Your class doesn't take any arguments. You can take a look at functions here for a simple example.

woooee 814 Nearly a Posting Maven

Here is a link to simple on-line tutorial. See the explanation under "Functions". You should book mark this link for future reference http://hetland.org/writing/instant-python.html

woooee 814 Nearly a Posting Maven

Since you are running an app outside of the Python environment, via os.system, the mouse is controlled by the external app that you are running.

woooee 814 Nearly a Posting Maven

You have to install pygtk, which is the python binding to GTK, for the 2.5 version. If you look in the /usr/lib/ directory for 2.6.4 you should see a directory for pygtk. I would first search the Fedora repositories as it should have both Python2.5 and PyGTK for 2.5.

woooee 814 Nearly a Posting Maven

Works fine for me on Monday AM. Try pasting the url into the browser.

woooee 814 Nearly a Posting Maven

Perhaps I am missing something, but the following code should work. But once you get past the precision of floating point numbers you will have to use the decimal module whichever way you do it.

import decimal
x = decimal.Decimal("2.4999999999999999999999999")
whole, remain = divmod(x, 1)
if remain >= decimal.Decimal("0.5"):
    whole += 1
print whole
woooee 814 Nearly a Posting Maven

I prefer to bind the button to a function that returns the desired variable, but it is somewhat personal preference.

from Tkinter import *

class ChooseVideoFiles:
    def __init__(self, root):
        canv = Toplevel(root)
        canv.geometry("+150+250")
        title = Label(canv, 
              text = "Select 3 videos with specified or a bit longer length",
              font = ("Helvetica", 10, "bold")).grid()
        self.buttons(canv)
        exit = Button(canv, text='Exit', command=top.quit).grid(row=5,column=0)

    ##-------------------------------------------------------------------         
    def buttons(self, canv):
        b_row=1
        b_col=0
        parameter_list = [ [2, "2 minutes", "Line 1"], \
                           [3, "3 minutes", "Line 2"], \
                           [5, "5+ minutes", "Line 3"] ]

        for param in parameter_list:
            b = Button(canv, text=param[1])
            b.grid(padx=3, pady=5, row=b_row, column=b_col, sticky=W)
            lab = Label(canv, text=param[2]).grid(padx=93, pady=5, 
                        row=b_row, column=b_col, sticky=W)

            def handler ( event, self=self, button_num=param[0] ):
                return self.cb_handler( event, button_num )
            b.bind ( "<Button-1>", handler )

            b_row += 1

    ##----------------------------------------------------------------
    def cb_handler( self, event, cb_number ):
        print "cb_handler", cb_number                

top = Tk()
CV = ChooseVideoFiles(top)
top.mainloop()
woooee 814 Nearly a Posting Maven

You would have to use Tkinter or one of the other toolkits. An example http://tkinter.unpythonic.net/wiki/AutocompleteEntry

woooee 814 Nearly a Posting Maven

Use Tkinter's FileDialog (note that you double click a directory to show that directory).

from Tkinter import *
from FileDialog import FileDialog

def get_filename( dir = "" ):
    top = Tk()

    d = FileDialog( top )

    ##---  all arguments to .go are optional
    fname = d.go( dir )
    if fname == None :
        print "No file found", fname
        fname = "****"
    else :
        print "The file is %s" % (fname)

    return fname

##================================================================

if __name__ == '__main__':
    ret_filename = get_filename( "/home/")
    print "filename returned is %s" % (ret_filename)
woooee 814 Nearly a Posting Maven

Use root.withdraw

from tkinter import *
##from tkinter import ttk
from tkinter import messagebox

root = Tk()
root.withdraw()
answer = messagebox.askyesno(message="Are you thinking of the " + "data " + "?"
                             ,icon='question' ,title="My guess")
print(answer)
woooee 814 Nearly a Posting Maven

See this comment is tbone2sk's reply above.

Line 33
Python Syntax (Toggle Plain Text)
return windowSurface
return event
A method can not have more than one return statement, both of these variables can be returned as a tuple though.

The first culprit to check on is to see if "event" is returned because the second return will never execute. Add something like this to statements that expect to receive "execute" from a function.

def menu():
    windowSurface = newscreen()
    event = newscreen()
    print event, type(event)

If you get "None" then something is wrong. I would suggest that you break this program up into small segments/functions and test each one individually before you do any more coding.

woooee 814 Nearly a Posting Maven

Can you just strip off the first and last parameter?

## path_file "".join(sys.argv[1:-1])

import os

test1 = ["program_name.py", "one/path/", "two_paths/", "three", "second_arg"]
path_file = "".join(test1[1:-1])
print path_file
if os.path.isfile(path_file):
    ## etc
woooee 814 Nearly a Posting Maven

These files are between 6 and 15 mb is size.

That's not very large by today's standards so I doubt that "MemoryError message" means running out of memory. Try running the program with a try/except and maybe you will get error messages that show what and where the error is, as not much can be done with what was presented.