So your file has one word per line?
The missing indentations are most like fault of your code editor.
What editor are you using?
So your file has one word per line?
The missing indentations are most like fault of your code editor.
What editor are you using?
Boa Constructor has very many features, for beginner takes time to get familiar. I use it, but some things are not intuitive and hard to find in the extensive menu. You can try it, and I can answer some of your questions. I think vegaseat knows more about it.
You can of course also use Boa for your regular console programs too, it has nice editor/IDE. I think Boa is great tool to learn wxPython things.
Try to download the installer exe for Windows from:
http://downloads.sourceforge.net/boa-constructor/boa-constructor-0.4.4.win32.exe
Decided to start my own thread rather than hijack thread "Sorting"
I followed ghostdog74 advice and used module re to extract numeric strings:
import re
data_raw = """[20]
[ 35+ ]
age = 40
(84)
100kg
$245
"""
# use regex module re to extract numeric string
data_list = re.findall(r"\d+",data_raw)
print data_list # ['20', '35', '40', '84', '100', '245']
That works fine, but when I change to floating point number:
import re
data_raw = """[20]
[ 35+ ]
age = 40
(84)
100kg
$245.99
"""
# use re to extract numeric string (however, float split at '.')
data_list = re.findall(r"\d+",data_raw)
print data_list # ['20', '35', '40', '84', '100', '245', '99']
How can I make re handle floating point numbers?
Thanks this info ghostdog! You must be one great regex expert!
re.findall(r"(\d+)",data_raw) works great on raw_data, but when I changed 40 to 40.5 it gave me [..., '40', '5', ...]
Looks like '\d+ only works on integers.
Do you have any suggestions for floats?
Maybe I should start new thread? Did start own thread see "Extract Numbers from Data Stream"
Thanks in advance!
Henri
Any hints on how you solved it?
Right now the main thing wrong are all the missing indentation that Python uses to block code.
It would be nice to know what 'wordlist.txt' looks like.
I looked at Ene's wxPython remake of vegaseat's fancy Tkinter GUI "Hello World!" code, and used the Boa Constructor IDE to do this. It took only a few minutes to create this wxPython code, since Boa has a drag/drop frame builder and writes most of the code:
# fancy "Hello World!" wxPython code generated mostly by Boa Constructor
# Boa Constructor (needs wxPython, has drag/drop frame builder, debugger etc.)
# Further development may have stopped. Download free from:
# http://freshmeat.net/redir/boa-constructor/832/url_zip/boa-constructor-0.4.4.zip
#Boa:Frame:Frame1
import wx
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1STATICTEXT1,
] = [wx.NewId() for _init_ctrls in range(4)]
class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(396, 174), size=wx.Size(391, 178),
style=wx.DEFAULT_FRAME_STYLE, title=u'Hello World from DaniWeb!')
self.SetClientSize(wx.Size(383, 138))
self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
label=u' Hello World! ', name='staticText1', parent=self,
pos=wx.Point(0, 0), size=wx.Size(385, 84), style=0)
self.staticText1.SetBackgroundColour(wx.Colour(255, 255, 0))
self.staticText1.SetForegroundColour(wx.Colour(255, 0, 0))
self.staticText1.SetFont(wx.Font(36, wx.SWISS, wx.NORMAL, wx.NORMAL,
False, u'Comic Sans MS'))
self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label=u'white on blue',
name='button1', parent=self, pos=wx.Point(56, 96),
size=wx.Size(96, 28), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
id=wxID_FRAME1BUTTON1)
self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label=u'blue on green',
name='button2', parent=self, pos=wx.Point(216, 96),
size=wx.Size(103, 28), style=0)
self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
id=wxID_FRAME1BUTTON2)
def __init__(self, parent):
self._init_ctrls(parent)
def OnButton1Button(self, event):
# I had to add these lines, Boa generates the rest
self.staticText1.SetBackgroundColour("blue")
self.staticText1.SetForegroundColour("white")
self.staticText1.SetLabel(" Hello World! ")
#event.Skip()
def OnButton2Button(self, event):
# I had to add these lines, Boa generates the rest
self.staticText1.SetBackgroundColour("green")
self.staticText1.SetForegroundColour("blue")
self.staticText1.SetLabel(" Hello World! ")
#event.Skip()
if __name__ == '__main__':
app = wx.PySimpleApp()
wx.InitAllImageHandlers()
frame = create(None)
frame.Show()
app.MainLoop()
This will print your PYTHONPATH. If the path you want is not listed, and it shouldn't be because your program isn't found, then you have to use sys.path.append to add it.
import sys path_list= sys.path for eachPath in path_list : print eachPath
PYTHONPATH is only used by Python internally to find modules etc.
This person wants to use Window's Environment Variable.
This looks more like something your internet provider is doing to keep cost down!
Not too long ago I wrote Python program to check the onset and degree of color blindness. Actually posted the beginnings of it as snippet here:
http://www.daniweb.com/code/snippet457.html
If you are interested in things medical, you can check out BioPython at:
http://biopython.org/wiki/Main_Page
Pack it into a function then you can use it again and again:
def get_integer():
'''loops until integer value is entered, then returns it'''
while True:
try:
num = int(raw_input("Enter integer number: "))
return num
except ValueError:
print "Please, enter integer number!"
# get integer value from the user
val = get_integer()
print val
This puts little more light on it:
def fib(n):
print "Computing fib:", n
if 0 < n < 3:
value = 1
print "1Returning value: ", value
elif n == 0:
value = 0
print "2Returning value: ", value
else:
value = fib(n-1)+fib(n-2)
print "3Returning value: ", value
return value
def main():
n = input("Enter a positive number: ")
print fib(n)
main()
I could do the same in assembly, wow assembly look how powerful it is!
If you had used assembly language you would now be 10% done!
If you have a PC with Windows, you can use wxPython to read PDF files, check:
http://www.daniweb.com/code/snippet618.html
I think wxPython demos were written by my C++ professor or his father. He always uses the C++ trick of putting in obscure header files, to make student's life harder!
I have simplified some code that works without those extra imports at:
http://www.daniweb.com/code/snippet615.html
Lists are mutable, Dictionaries are not.
That is not true! Dictionaries are mutable! However, you cannot use mutable objects like lists and yes dictionaries for the key. Dictionary values can be most anything. Study some more and experiment with this interesting container. If you get stuck, ask more questions!
Rather than putting your selected line into Label, put it into Entry. Now you can edit it. Bind the Entry to double mouse click to load it back into Listbox at the index sel[0] you have.
I think it depends on the version of Windows XP. I can repeat vegaseat's observation on my folks old desktop computer, but import uses the updated pyc file right away on a friend's brandnew laptop with the latest version of Windows XP.
Does anyone now how to display the version of Windows XP?
Note: Also found out that the module name and the file name have to absolutely match (case sensitive).
When you do GUI programming, you will find another endless loop usually called mainloop(). This is the loop that continuously scans for windows events like mouse clicks, mouse position, button clicks, key presses and so on.
The mainloop() is not truely endless, when you click on the little x on the upper right corner of the window frame it quits.
For German characters I have found it simpler to replace them with acceptable equivalents. Here is an example:
# -*- coding: iso-8859-15 -*-
str1 = 'Activest-Aktien-Großbritannien'
print str1 # test
str1 = str1.replace('ß', 'ss')
print str1 # test
str2 = 'Überländliche Fracht'
print str2
str2 = str2.replace('Ü', 'Ue')
str2 = str2.replace('ä', 'ae')
print str2
My advice, use the little utility at:
http://www.daniweb.com/code/snippet499.html
Since this is GUI program you need to change 'console' to 'window' and give your filename .pyw extension.
You might have to destroy the dialog after it has been used:
### uncomment the following 2 lines of code and
### the popup menu will not appear on fc5
if dlg.ShowModal() == wx.ID_OK:
# do something
thisresult = "a file was selected"
dlg.Destroy()
### ######################
Here are simple programs. The console version:
# console sales tax program
while True:
price = float(raw_input("Enter purchase price: "))
# prevent division by zero error
if price != 0:
break
else:
print "price can not be zero!"
tax = float(raw_input("Enter sales tax paid: "))
percent = 100 * tax / price
print "You paid %0.3f%s sales tax" % (percent, '%')
Now the Tkinter GUI version:
# Tkinter sales tax program
from Tkinter import *
import tkSimpleDialog
# the basic window
root = Tk()
# create label for result
label1 = Label(root)
# position the label in window
label1.grid(row=0, column=0)
# ask for needed data with dialog window
# the askfloat dialog window makes certain you entered floating point value
# and also prevents you from entering zero which would give divide by zero error
price = tkSimpleDialog.askfloat("Price", "Enter purchase price:", parent=root, minvalue=0.01)
tax = tkSimpleDialog.askfloat("Tax", "Enter sales tax paid:", parent=root)
percent = 100 * tax / price
result = "You paid %0.3f%s sales tax" % (percent, '%')
# display result string in label1
label1.config(text=result)
# event loop needed by GUI, checks for mouse and key events
root.mainloop()
Accidental endless loops are the once you have to watch out for. The 'while loop' is more prone to this either through faulty escape logic or accidental use of the control variable:
# accidental endless loop
# this is okay in Python
for k in range(10):
k = 2
print k
# but not in C ...
"""
// accidental endless loop in C
#include <stdio.h>
int main()
{
int k;
for(k = 0; k < 10; k++)
{
k = 2;
printf("%d", k);
}
return 0;
}
"""
# the C 'for loop' behaves more like this
# now you have accidental endless loop
k = 0
while k < 10:
k = 2
print k
The easiest way would be to use:
import os
os.system("echo $BASH_VERSION")
For your information, a few nice folks are working on a 'Python Tkinter GUI Builder' (ptkgb), that allows you to drag and drop Tkinter widgets on one form similar to the Delphi RAD or MS Visual stuff. Take a look at:
http://sourceforge.net/projects/ptkgb/
Expanding on mawe's formula builder, this is my contribution to the equation solver:
# evaluate equation like 3x^2+2(3x-2) = 0
import re
# look for digit before alpha and '('
pattern = re.compile("(\d)([A-Za-z(])")
formula_raw = "3x^2+2(3x-2)"
# insert '*' between digit and alpha or '('
formula = re.sub(pattern, r"\1*\2", formula_raw)
print formula # '3*x^2+2*(3*x-2)'
# take care of power symbol ^
if '^' in formula:
formula = formula.replace('^', '**')
print
print "formula =", formula # '3*x**2+2*(3*x-2)'
# test it with for loop ...
for x in range(-5, 5):
if 'x' in formula:
formula2 = formula.replace('x', str(x))
#print formula2 # test
print "x = %s --> %s" % (str(x), eval(formula2))
print
# narrow x value down ...
for x in range(0, 100):
x = x/100.0
if 'x' in formula:
formula2 = formula.replace('x', str(x))
result = eval(formula2)
# when result crosses zero line stop
if result > 0.0:
print "x = %s --> %s" % (str(x), result)
break
Mawe sure knows how to keep it simple and elegant! Here is my contribution to mawe's original horizontal bar graph, I added one line of actual data value markers to the end, still simple:
data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]
# pad each bar with spaces to total length of max(data), here 20
bar_list = []
for x in data:
str1 = "#" * x
# space pad to the right
str2 = str1.ljust(max(data))
bar_list.append(str2)
# test it, also show data value marker at end
for index, item in enumerate(bar_list):
print item, ' -', data[index]
MSVCR71.dll is the Microsoft runtime C++ library. I don't think Py2Exe is going to mess with that! You can distribute that file, but you cannot change it or get the wrath of big MS!
Jython compiles Python source code down to Java bytecodes which can run directly on a JVM. You have to use the Java utility corresponding to Py2Exe! Py2Exe only handles Python byte code.
Looking through your traceback message, the file it can't find is _core_.pyd, which is a Python DLL. On my machine this file is in the C:\Python25\Lib\site-packages\wx-2.6-msw-unicode\wx\ folder. Notice that I have a slightly older version of wxPython for Python25. You might want to check your corresponding folder for this .pyd file
The only other DLL I can think of is the interpreter itself in Python25.dll, also in C:\Windows\System32\.
Py2exe puts that right into the .exe file depending on your setup options.
Did you run py2exe with the windows program and single-exe option?
Sorry, I don't use Tkinter much, mostly wxPython. It looks to me that in (3) you are overwriting whatever has been in self.level_string with "Level: ".
Nice wxPython code! MSVCP71.dll is the Microsoft C++ runtime library used by wxPython. You should install it in C:\WINDOWS\system32\. That should take care of your problems.
I noticed you are using Python25, make sure that wxPython and Py2Exe are also for that version of Python.
Seems that Linux folks use GTK and pygtk for GUI work. It looks like a good GUI, but I use the Windows OS and the whole installation process of GTK/pygtk and all the additional required things is very cumbersome.
I personally like wxPython a lot. Why did you choose to go with GTK?
I am studying C++ right now in school (not my choice), and being used to Python the endless type declarations, memory allocations, and pointer this, and pointer that, to achieve very simple stuff, is cumbersome at best. Function arguments are handled with such elegance in Python!
I keep reading that MySQL is hard to program with, no matter what computer language you use. Hope you find someone familiar with MySQL.
The two functions
num = input("Enter a number: ")
and
name = raw_input("Enter a name: ")
are for the user to enter number or name from the console.
Please use code blocks.
import string
def main():
#data = raw_input("H:\harry.txt") # use data = raw_input("Enter file name: ")
# what you want is most likely this
# expects the file to be in the working/current directory
data = "Harry.txt"
infile = file(data, 'r')
data_file = infile.read()
number_of_characters = len(data_file)
print "The number of characters in your text is", number_of_characters
list_of_words = string.split(data_file)
number_of_words = len(list_of_words)
print "The number of words in your text is", number_of_words
infile.close()
secondfile = file(data, 'r')
line_of_text = secondfile.readlines()
print line_of_text
number_of_lines = len(line_of_text) # corrected lines_of_text to line_of_text
print "The number of lines in your text is" , number_of_lines
infile.close()
main()
Rightclick the IDLE icon and check Properties. You may notice that it still wants to run under Python23. Create a shortcut of Idle.pyw in the Python25/Lib/idellib/ directory and drag it onto your display panel. Use this new icon to run IDLE.
Write Human vs. Computer Battle Ship Game in Python. Tkinter should/could do it for the graphics.
Possible setup:
Battleship (1) = 4 adjoining squares
Cruiser (2) = 3 adjoining squares
Destroyer (3) = 2 adjoining squares
You could save important details of player (player, hitpoints, treasures, weapons etc.) to a file before you exit the game. Now you have to also write your code to accept any saved game as option when you start.
Tkinter that comes with Python allows graphics, another one is PIL also PyGame. Those are freee downloads.
The question is about rounding off the returned value and not rounding off while displaying. Read the first post.
This does not make any sense, if the return value is double or float you can not guarantee precision to be 38.3 it most like will be 38.2999999 or something like that.
The rounding is done in your display function. Here is C example:
// percent calculation, wants 100 * 90/235 --> 38.3 %
#include <stdio.h>
double CalculatePercentage(double TotalComponent, double PartialComponent)
{
return 100*PartialComponent/TotalComponent;
}
int main()
{
printf("100 * 90/235 --> %0.1f%c", CalculatePercentage(235, 90), '%');
getchar(); // wait for key press
return 0;
}
And here is C++ example:
// percent calculation, wants 100 * 90/235 --> 38.3 %
#include <iostream>
#include <iomanip>
using namespace std;
double CalculatePercentage(double TotalComponent, double PartialComponent)
{
return 100*PartialComponent/TotalComponent;
}
int main()
{
cout.setf(ios::fixed);
cout<< setprecision(1) << "100 * 90/235 --> " << CalculatePercentage(235, 90) << '%' << endl;
cin.get(); // wait for key press
return 0;
}
If you have Windoze machine you can use MSvfw32.lib for Dev_Cpp code example see:
"An AVI Media Player (Dev-C++)"
http://www.daniweb.com/code/snippet95.html
Chris, this approach would avoid the repetition of the room description and make the code shorter. Here is a test code:
gold = 0
gotGold_reading = 0
def reading_room():
global gold
print " Current Gold = ",gold
print " You are in a large reading room ..."
rea_desc()
#prompt_rea()
def rea_desc():
print ''' The room is stuffed with novels and poetry books on every
every shelf. There is a large table in the middle of the room.
It has a reading lamp, and a cluster of books scattered about
on top. The exits are (N)orth and (E)ast.
Type 'help' for a full list of commands.'''
print
prompt_rea()
def prompt_rea():
global gold
global gotGold_reading
prompt_r = raw_input("Type a command: ").lower()
# etc etc ...
reading_room()
You have two similar lists and want to see what items are in list1 that are not in list2 and vice versa. The trick is to convert them into sets and take the difference:
color_list1 = ["red","green","blue","purple","yellow","violet","white","cyan",
"magenta","turquoise","black","lightblue","grey","lightgrey","darkgrey",
"lightgreen","teal","pink","darkblue","darkred","darkgreen","orchid","beige"]
color_list2 = ["red","green","blue","purple","yellow","orchid","grey","white",
"cyan","magenta","turquoise","limegreen","lightblue","lightgrey","darkgrey",
"lightgreen","tan","darkblue","darkred","darkgreen","violet","pink","beige"]
print "color_list1 =", color_list1
print "-"*70 # 70 dashes
print "color_list2 =", color_list2
print "-"*70
# convert lists to sets
color_set1 = set(color_list1)
color_set2 = set(color_list2)
print "These are the colors of color_list1 that are not in color_list2:"
print color_set1 - color_set2
print "-"*70
print "These are the colors of color_list2 that are not in color_list1:"
print color_set2 - color_set1
If you have simple English word like:
str1 = 'supercalifragilisticexpialidocious'
How would you form string that has every second letter in capital (upper case).
I have used Python and I am learning C++. Programs that are just a few lines of code in Python are nightmares in C++, like splitting sentence into words and loading them into array of strings dynamically.
I have used pygtk one little and have found these good resources:
Recommended reading for Python+GTK users
PyGTK 2.0 Tutorial by John Finlay
download from: http://www.pygtk.org/dist/pygtk2-tut.pdfalso:
PyGTK FAQ Index
at: http://www.async.com.br/faq/pygtk/index.py?req=index