snippsat 661 Master Poster

in ruby everything is an object, unlike Python where the primitives are, well, primitive

Maybe you should look thing up before you talk.
http://www.diveintopython.org/getting_to_know_python/everything_is_an_object.html

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute doc, which returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

As with Python, in Ruby,... Everything is an object
http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/
So there you have it from Ruby's own website: in Python everything is an object

.

snippsat 661 Master Poster

There is a bug with python 3.2 and command line output from input()
It put on a '\r' character on input() when run from command line.
http://bugs.python.org/issue11272
This will be fix in in 3.3 (r88530) and 3.2 (r88531). Others versions are not affected.

A temporay fix is to use strip()
guess = input('Your guess\n').strip()

snippsat 661 Master Poster

Just a note,dont use singel \ it can be used as an escape character.
For windows always python C:\\my_script\\script.py or python C:/my_script/script.py

snippsat 661 Master Poster

Just a note collections Counter will always sort in descending count order.
Here i also show most_common(),no we now that all word after 'it' has 1 as count.

from collections import Counter
from string import punctuation

text = """\
If you see a turn signal blinking on a car with a southern license plate,
you may rest assured that it was on when the car car car car car was purchased.
"""

text = ''.join([c for c in text if c not in punctuation])
print Counter(text.split()).most_common(6)
#-->[('car', 6), ('a', 3), ('you', 2), ('was', 2), ('on', 2), ('it', 1)]
vegaseat commented: nice +13
Lardmeister commented: good code +6
e-papa commented: Good one. +1
snippsat 661 Master Poster

Hello. I have been trying to run a simple script in Windows 7 DOS using the python command

Dont call it DOS because it`s a long time since windows had DOS.
Windows 98 is the last version based on MS‑DOS.

Command Prompt is sometimes incorrectly referred to as "the DOS prompt" or as MS-DOS itself. Command Prompt is a Windows program that emulates many of the command line abilities available in MS-DOS but it is not actually MS-DOS.

How do I set PYTHONPATH?

Add PYTHONPATH to Environment Variables.
http://www.windows7hacker.com/index.php/2010/05/how-to-addedit-environment-variables-in-windows-7/
To path add ;C:\python32\;C:\python32\scripts;
If install in other folder than this(default),type in correct path to that folder.
A good python editor make it easier to run code,look at pyscripter.
http://code.google.com/p/pyscripter/

snippsat 661 Master Poster

As tony posted there is much info on this site.
Take a look The Python Standard Library
All this is build-in an you can import and use it.

snippsat 661 Master Poster

I have seen someone else in a other forum had the same problem with python 3.2
Is correct when run from IDLE,and the problem is when run from command line.
This is python bug tracker,if you want to look for or report a bug.
http://bugs.python.org/

snippsat 661 Master Poster
def myfunc(*args):
    return sum(args)

print myfunc(10,10,1,10,10,10,10,10) #71
snippsat 661 Master Poster

Thank makes it a little bit better but I don't need to print the numbers on the file for this program...

Yes you dont need to print number,i tok it with just to explain how this work.

snippsat 661 Master Poster

You can look at this example.

'''num.txt-->
1 2 3 4 5
'''

with open('num.txt')as f:
    for item in f:
        n = item.strip().split()
        print sum((int(i) for i in n)) #15

If you use print n before last line you see
So we have stript of newline(\n) and split the number up.
As you see now all number are string.
On the last line convert to integer and use sum() to calulate those numbers.

TrustyTony commented: Good teaching (some 'new reputation') +13
snippsat 661 Master Poster

For stand alone application there are py2exe,cx_Freeze,PyInstaller.
Gui2exe is good with a Gui interface for all this installer.
And finish it with a good installer like inno-setup

You also have Portable python than can run python code without python installed.
And as we know all linux distros and mac version comes with python pre-installed.

snippsat 661 Master Poster

What OS(operating system) do you us?
For windows the brainless binary install(exe,msi) next,next...finish.

List of diffent OS install at pygame site.
http://www.pygame.org/install.html

e-papa commented: good one. +1
snippsat 661 Master Poster

I'd like to know what it's used for. I think it's mostly used for web application's.

Python is used in all application you can think off.
Python is strong in web application's as you say with many good Web Frameworks.
http://wiki.python.org/moin/WebFrameworks
Pyhon also have strong GUI-toolkit like wxpython,PyQT,PyGTK and bulid-in Tkinter.

I'd also like to know if it has a runtime environment For example, Java's runtime environment is the JVM(Java Virtual Machine), at least I think so.

To run a Java program, you must have Java's Runtime Environment installed on your machine.
To run a Python program, you must have Python's Interpreter installed on your machine.
Allmost all linux distros an mac comes with python pre install.

Python easy to install just 1min and it`t ok on windows.
For stand alone application there are tool like py2exe,cxfreez,Gui2exe,portable python also using installer like inno-setup for making a good looking installer.

Also, is Python a language that's actually used? Like do many companies use Python?

http://www.python.org/about/quotes/

Python is used successfully in thousands of real-world business applications around the world, including many large and mission critical systems. Here are some quotes from happy Python users:

e-papa commented: Goos one. +1
snippsat 661 Master Poster

Wxpython do like very much,feel most pythonic.
Robin Dunn the main developer dos a very good jobb with wxpython.
Just look at wxpython maling list,the developers answer daily on question.
Documation and tutorials is a lot more for wxpython than PyQt and PyGTK.

Tkinter the build GUI-toolkit is ok,but the ugly look Tkinter has in windows is not ok at all for me.
Tkinter lack also some of the advance features in the other gui-toolkit.

Some program that use (wxpython/wxwxwidgets) as GUI.
Dropbox- TrueCrypt - Digsby

snippsat 661 Master Poster

Dont use file as variable is a reserved keyword for python.
So for this script under to work,test.py an words.txt need to be in same folder.

#test.py
my_file = open('words.txt') #Remeber '' open take string as argument
print my_file.read()
my_file.close()

Let say that words.txt is not in same folder as test.py
Then you need to give correct path to words.txt
Here words.txt is placed in folder c:\test
Remeber not use single \ when give path to file,python can see \ as an escape character.
c:\\test or c:/test not c:\test

#test.py
my_file = open('c:/test/words.txt')
print my_file.read()
my_file.close()

The most common way in python today is to use with open()

with open('words.txt') as f:
    print f.read()

With this method you dont need to close() file object,as you see i do in script over.

e-papa commented: Thanks +1
snippsat 661 Master Poster

Very simply program but I can't get it to work. I know sure how to write the code.

You have to post code,how do you think we can help you?.
We are not mind readers.

but I can't get it to work.

Python always give you Traceback if something goes wrong,this is important to understand.
That you dont get the output you want can be a design fail in code.
But this no one can know,because you just say something dos not work.
An example of Traceback.

>>> k
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
NameError: name 'k' is not defined
>>> #So we need to define k
>>> k = 5
>>> k
5
>>>
snippsat 661 Master Poster

e-papa look at my code and your code,it`s has no diffrence.
So read all post better next time.

snippsat 661 Master Poster

A good python IDE editor will help you more than notepad++.
For windows pyscripter or linux SPE

snippsat 661 Master Poster

A parser like BeautifulSoup or lxml to exctract url.

url with some parameters.

http://docs.python.org/library/urlparse.html
http://atomized.org/2008/06/parsing-url-query-parameters-in-python/

snippsat 661 Master Poster
#python 3
def main():
    i = int(input())  #input in python 3 return a string
    print(i + 1)      #now it will add 1 to input     

#Call main() function
main()
snippsat 661 Master Poster

but is there any python equivalent to the Java .jar files?

Yes .py files.
So think of this jar files will not work if not JRE (Java Runtime Environment) is installed.
To make jar files you need JDK (Java Development Kit)

Py files will not work if python is not installed.
Jus the same as with jar files.

Is there any way to produce an executable file containing everything within it like Java's .jar's?

jar are not executable without java installed,just the same as .py files is not executable without python installed.

snippsat 661 Master Poster

http://stackoverflow.com/questions/3270209/how-do-i-make-tkinter-support-png-transparency
Wxpython has good support for transparent image,and may be a better choice.
For me there has never been a choice i find wxpython much better than Tkinter.
The ugly look of Tkinter in windows is not ok at all.
PyQt and pyGTK shold also has support for this.

snippsat 661 Master Poster

Why do you need to do system call with command line grep?,you can easily write this without it.
Python has lot more power an dont need command line call like this to do this simple task.

snippsat 661 Master Poster

Try with regex,and use an compile() regex with finditer() Look like this.

import re

text = """\
Hi,i have car.
I drive to work every day in my car.
This text will find all car,car.car?!car."""


r = re.compile(r'\b(car)\b')
for match in r.finditer(text):
    print match.group()
snippsat 661 Master Poster

You have some mistake,and use code tag.
See if this help.

def main():
    phrase = input("Enter a sentence:")
    words = phrase.split() #Forget ()
    wordCount = len(words)
    print("The total word count is: %s" % wordCount) #You have to include wordCount in print
main()
snippsat 661 Master Poster

Currently, it worked fine with a dozen documents tested. But I think it's not robust enough. Do you know any library than can do the job?

BeautifulSoup is very robust,not many parser are so good.
You have lxml that is good,it also has BeautifulSoup and html5lib build in.
lxml has also xpath.

snippsat 661 Master Poster

Yes using time or datetime is the standar way,but i am pretty sure that he can not use that in this school assignment.
Because task like this has been posted many times before,and no module could be used.

snippsat 661 Master Poster

Thank You for the help! By the way, I was just wondering how would you write this program with lists instead of dictionary?

>>> n = [i+1 for i in range(12)]
>>> m = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
>>> z = zip(n,m)
>>> z
[(1, 'Jan'),
 (2, 'Feb'),
 (3, 'Mar'),
 (4, 'Apr'),
 (5, 'May'),
 (6, 'Jun'),
 (7, 'Jul'),
 (8, 'Aug'),
 (9, 'Sep'),
 (10, 'Oct'),
 (11, 'Nov'),
 (12, 'Dec')]
>>> m, d, y = '4/11/2010'.split('/')
>>> for i in range(len(z)):
...     if int(m) in z[i]:
...         print z[i][1]
...         break
...     
Apr
>>>
snippsat 661 Master Poster

Yes Kur3k soultion is ok,a little long that last print line.

dic = { 1  : "Jan",
        2  : "Feb",
        3  : "Mar",
        4  : "Apr",
        5  : "May",
        6  : "Jun",
        7  : "Jul",
        8  : "Aug",
        9  : "Sep",
        10 : "Oct",
        11 : "Nov",
        12 : "Dec" }

def replace_date(month = 0):
    return dic[month]

m, d, y = '4/11/2010'.split('/')
#print m, d, y #Test print
print '%s, %s, %s' % (replace_date(int(m)), d, y)
#-->Apr, 11, 2010

@nightrev you dident try to hard at this school task and where maybe lucky to get a finish solution for your answer.

snippsat 661 Master Poster

It`s possible to get what you what with regex to,as i posted over there are better tool.
But for fun here is the regex solution.

import re

html = '''\
'<div class="BVRRLabel BVRRRatingNormalLabel">Customer Rating</div><div class="BVRRLabel BVRRRatingNormalLabel">Value for Price</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Picture Quality</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Ease of Use</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Features</div>'''

find_text = re.findall(r'\>(\w.+?)\<', html)
print find_text
#--> ['Customer Rating', 'Value for Price', 'Picture Quality', 'Ease of Use', 'Features']
snippsat 661 Master Poster

Regex an html are not best friend.
Read the best answer out there(bobince)
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

A parser is the right tool for this,here is an example with BeautifulSoup.

from BeautifulSoup import BeautifulSoup

html = """
string_feature = '<div class="BVRRLabel BVRRRatingNormalLabel">Customer Rating</div><div class="BVRRLabel BVRRRatingNormalLabel">Value for Price</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Picture Quality</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Ease of Use</div>
<div class="BVRRLabel BVRRRatingNormalLabel">Features</div>"""

soup = BeautifulSoup(html)
tag = soup.findAll('div')
print [tag[i].text for i in range(len(tag))]

"""Output-->
[u'Customer Rating', u'Value for Price', u'Picture Quality', u'Ease of Use', u'Features']
"""
snippsat 661 Master Poster

Use urlretrieve .

>>> from urllib import urlretrieve
>>> help(urlretrieve)
Help on function urlretrieve in module urllib:

urlretrieve(url, filename=None, reporthook=None, data=None)

Example.

from urllib import urlretrieve
urlretrieve('http://gdimitriou.eu/wp-content/uploads/2008/04/google-image-search.jpg', 'google-image-search.jpg')
debasishgang7 commented: It worked fine..Thanks a lot.. +2
snippsat 661 Master Poster

A couple way is split at / or use a regex.

>>> d = '1/2/2010'.split('/')[2]
>>> d
'2010'

>>> import re
>>> s = re.search(r'\d{4}', '1/2/2010')
>>> s.group()
'2010'
>>>
snippsat 661 Master Poster

You are doing some some thing that are not good at all.
assert lin == "Acatari, Aiud, 72.639\n"
Read about the use of assert and that you use == make it strange¨.
assert <<expression, error_message>> is a form of error checking.
It raises an exception if the expression evaluates to false and include the error message.

If you want to convert back to tuple it look like this.
I think you should do some basic reading about python.

def line_to_entry(lin):
    lin = tuple(lin.split(', '))
    return lin

if __name__ ==  "__main__":
    lin = "Acatari, Aiud, 72.639\n"
    print line_to_entry(lin)
snippsat 661 Master Poster

Or i got it again confused?

It`s right and you could use an other name so it`s not entry as an function argument an a variable name.

def entry_to_line(tuple_in):
    entry = ', '.join(map(str,tuple_in))
    return entry

#re = ('Acatari', 'Aiud', 72.639)
test = (1,2,3)
print entry_to_line(test)
print type(entry_to_line(test))
snippsat 661 Master Poster

Using tonyjv'advice i tried the fallowing with the code for the first function

You are making some big mistake when you making it a fuction.
You are putting in an argument to function that you not use inside the function entry
And you making a recursive call of the function return entry_to_line .

def entry_to_line():
    re = ('Acatari', 'Aiud', 72.639)
    entry = ', '.join(map(str,re))
    return entry

print entry_to_line()

#Or with list comprehension
def entry_to_line():
    re = ('Acatari', 'Aiud', 72.639)
    entry = ', '.join([str(i) for i in re])
    return entry

print entry_to_line()

or the second one i tried to find a way to convert from string to tuples for he first time in shell

No you are not it is a tuple and you are using a tuple.

>>> a = ('Acatari', 'Aiud', 72.639)
>>> type(a)
<type 'tuple'>

>>> b = ', '.join(map(str, ('Acatari', 'Aiud', 72.639)))
>>> type(b)
<type 'str'>
>>> b
'Acatari, Aiud, 72.639'

>>> c = ', '.join([str(i) for i in ('Acatari', 'Aiud', 72.639)])
>>> type(c)
<type 'str'>
>>> c
'Acatari, Aiud, 72.639'
>>>
snippsat 661 Master Poster

The problem in python 3 code is that you are comparing integer with string. input() in python 3 return a string same as raw_input() in python 2. input() in python 2 return an integer.
This will work

answer = int(input("> ")) #make input return an integer

Or you can cast it to an integer later.

if int(x) == 1:

Read about the differnce.
http://diveintopython3.org/porting-code-to-python-3-with-2to3.html

Use 4 space as indentation in your code,not 8.

vegaseat commented: nice +13
snippsat 661 Master Poster

TreeCtrl is really not meant to interact with filesystem.
wx.FileDialog is used to display files.

snippsat 661 Master Poster

This way in my code will save it in format you want.

with open('new_file.txt', 'w') as f:
    f.write('\n'.join(l))
snippsat 661 Master Poster

1. input ask user for date
2. ouput add three weeks to the input

Look at the datetime module for this.

>>> import datetime
>>> now = datetime.date(2011, 3, 5)
>>> difference1 = datetime.timedelta(days=21)
>>> print "3 weeks in the future is:", now + difference1
3 weeks in the future is: 2011-03-26
>>>
snippsat 661 Master Poster

Here is one way.

import re

'''num.txt-->
name2,number2;name3,number3;name1,number1
'''

with open('num.txt') as f:
    l = [i.strip().split(';') for i in f][0]

print l  #Test print

def key_sort(string):
    result = re.split(r'(\d+)', string)
    for i in xrange(1, len(result), 2):
        result[i] = int(result[i])
    return result

l.sort(key=key_sort)
print l

"""Output-->
['name2,number2', 'name3,number3', 'name1,number1']
['name1,number1', 'name2,number2', 'name3,number3']
"""
snippsat 661 Master Poster

One with regex.

import re

data = '''\
Correct for Detector Non-linearity: No (USB2E7196)
Correct for Stray Light: No (USB2E7196)
Number of Pixels in Processed Spectrum: 2048
>>>>>Begin Processed Spectral Data<<<<<
339.09 0.00
339.48 184.72
339.86 186.46
340.24 187.76
340.63 189.11
341.01 190.97
...
...
1023.36 196.86
1023.65 196.36
>>>>>End Processed Spectral Data<<<<<'''

r = re.compile(r'(\d+\..+)')
for match in r.finditer(data):
    print match.group()

'''Output-->
339.09 0.00
339.48 184.72
339.86 186.46
340.24 187.76
340.63 189.11
341.01 190.97
1023.36 196.86
1023.65 196.36
'''
snippsat 661 Master Poster

I dont use Tkinter so much,wxpyhon is my favoritt gui-toolkit in python.
You can look at this post here show sneekula and vega the use of tkinter listbox.
http://www.daniweb.com/forums/thread191210-2.html

snippsat 661 Master Poster

Look at cgi module.
http://docs.python.org/library/cgi.html
http://www.tutorialspoint.com/python/python_cgi_programming.htm

Most common way to work with HTML/websites is to use one of python Web framework.
http://wiki.python.org/moin/WebFrameworks

snippsat 661 Master Poster

In python call it list not array.
This line in my code and you have number of lines.
print len(my_list)

snippsat 661 Master Poster

Look into regular expression for changing filename.
Here is an example.

import re

files = '''\
lovelyname_annoying_chars.txt
Diename_annoying_charshard.txt
somenamename_annoying_chars.txt'''

new_files = re.sub(r'name_annoying_chars', '', files)
print new_files

"""Output-->
lovely.txt
Diehard.txt
somename.txt
"""
snippsat 661 Master Poster

Python string are immutable so delete it wont work.
You can replace it first character with nothing ''.

>>> s = "this is a really long string that is completely pointless. But hey who cares!"
>>> s.replace(s[0], '')
'his is a really long sring ha is compleely poinless. Bu hey who cares!'

Another way is make it a list and the do stuff you need,and take it back into a string again.

>>> s = "this is a really long string that is completely pointless. But hey who cares!"
>>> s = list(s)  #Make it a list
>>> del(s[0])    #Delete first character
>>> ''.join(s)   #Take it back to a string
'his is a really long string that is completely pointless. But hey who cares!'
snippsat 661 Master Poster

read() read the whole file into a string,so no need for lines in data
with open() close the file object auto.
So you can write it like this.

import urllib
data = urllib.urlopen('http://www.site.net/index.html').read()

with open('somefile.html', 'w') as f:
    f.write(data)
snippsat 661 Master Poster

Look at the output -ordi-
fiss gisse hd uc tb oa z
Do you see some character are missing?

I dont know how BirdaoGwra want the output,here are a couple of way.
fissgiss is one word in this,some more work is neede to split that to.
Pickle is way to save and get same output back,look at this.
http://www.daniweb.com/forums/thread343685.html

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + ' ' for i in l)
#--> fissgiss eh du ct bo az 

#---------------------------------------#
l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(''.join(i) + '\n' for i in l)

"""Output-->
fissgiss
eh
du
ct
bo
az
"""

Edit did see you post about output.

l = [['fiss','giss'], ['e','h'], ['d','u'], ['c','t'], ['b','o'], ['a','z']]

with open('w.txt', 'w') as f:
    f.writelines(' '.join(i) + '\n' for i in l)

"""Output-->
fiss giss
e h
d u
c t
b o
a z
"""
BirdaoGwra commented: I learned from him. +2
snippsat 661 Master Poster

Something you can look at,for doing financial calculations look at Decimal module.
http://docs.python.org/library/decimal.html

>>> number = 0.60
>>> print '%.2f' % number
0.60

>>> from decimal import *
>>> Decimal('0.60')
Decimal('0.60')
>>> Decimal('0.60') + Decimal('0.60')
Decimal('1.20')
>>> 
>>> print Decimal('0.60') + Decimal('0.60')
1.20
Archenemie commented: This post was concise and to the point with good examples +2