Fix your indentation is wrong in many places.
This has to be right in python.
danholding commented: very helpfull +1
snippsat 661 Master Poster
Fix your indentation is wrong in many places.
This has to be right in python.
You can take a look at this code.
Python also have a CSV module
my_list = []
with open('my_csv.txt') as f:
l = [i.strip().split(',') for i in f]
for i in range(len(l)):
my_list.append([int(n) for n in l[i]])
print my_list
print my_list[0][1] #Take out a number
print my_list[-1] #Take out last line of numbers
"""Output-->
[[2, 6, 3, 5, 0], [4, 0, 2, 5, 2], [5, 7, 9, 1, 0], [4, 6, 8, 2, 5], [2, 7, 9, 1, 6]]
6
[2, 7, 9, 1, 6]
"""
If you have question dont use a 6 year old post that has been marked solved.
Make a new post,just copy some code from older post if you have question about it.
what has fileHandle been replaced with in python 3.1
FileHandle is just a variable name used by vega.
You can use whatever name you want.
Here is the same code for python 3
# Testet work for python 3
# read a text file as a list of lines
# find the last line, change to a file you have
fileHandle = open ('test3.txt')
lineList = fileHandle.readlines()
fileHandle.close()
print (lineList)
print ("The last line is:")
print (lineList[len(lineList)-1])
# or simply
print (lineList[-1])
Or if we use an other name than FileHandle just f
# Testet work for python 3
# read a text file as a list of lines
# find the last line, change to a file you have
f = open ('test3.txt')
lineList = f.readlines()
f.close()
print (lineList)
print ("The last line is:")
print (lineList[len(lineList)-1])
# or simply
print (lineList[-1])
Postet over is a more modern solution by tony.
with open() close the file object auto,so no need for close()
thanks. What are major differences using Iron Python vs Python 2.6.6?
With ironpython you can use the .Net(framework)library.
Same as Jython there you can use java library.
You write in python,and import from Net library.
IronPython is an implementation of the Python programming language running under .NET and Silverlight. It supports an interactive console with fully dynamic compilation. It's well integrated with the rest of the .NET Framework and makes all .NET libraries easily available to Python programmers, while maintaining compatibility with the Python language. There also is Visual Studio tooling integration.
A couple of way to make it a list of integer and sort.
First one use list comprehension.
Second one use a function programming style with map().
>>> print sorted([int(i) for i in a])
[2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16]
>>> print sorted(map(int, a))
[2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16]
isnt this the shortest method
Not when you post C code in python forum.
>>> raw_input('enter a number: ')[::-1]
enter a number: 1234
'4321'
1) Is there any way to split into ?
>>> l[0].split() + l[1].split()
['a', 'b', 'c']
As postet over,repost your code with code tag.
And include the error message you get called(Traceback)
I have been told by a number of people to use xpath instead of regex for some of my regex searches.
What are you searching?
Some notes about XML/webpages here is regex not the right tool.
If you are parsing(searching) XML/html you should use beautifulsoup / lxml(has XPath built in) that is designed exactly for this purpose.
Why is regex bad for xml/html read this very good answer.
http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
When I run it, I have to type
setup py2exe
You run it as every other python code.
From your editor or command line python name_of_script.py
Dident get you pysnmp script to work.
Here is a working py2exe kode.
from distutils.core import setup
import py2exe
import sys
def py_exe(file_in=None):
if len(sys.argv) == 1:
sys.argv.append('py2exe')
setup(options = {'py2exe': {'compressed': 1, 'optimize': 2, 'ascii': 1, 'bundle_files': 3}},
zipfile = None,
## Can use console or window
## Filpath to '....py' or same folder as you run this py file from
console = [{'script': 'your_script.py'}])
py_exe()
You can also try Gui2exe.
http://code.google.com/p/gui2exe/
You should(most) read some tutorials/book about using classes.
The way you are doing is not god at all and wrong.
Like basic thing that a class need the self keyword.
Can write an example that makes more sense.
class numbers(object):
def addition(self,a,b):
self.a = a
self.b = b
return self.a + self.b
def multiply(self,a,b):
self.a = a
self.b = b
return self.a * self.b
class main(numbers):
calc = numbers()
num1 = 5
num2 = 10
print calc.addition(num1, num2) #15
print calc.multiply(num1, num2) #50
import re
text = '''\
#include "hello.h"
#include "d/hello.h"
#include "dir/hello.h"
#include "dir\hello.h"
#include <hello.h>
#include "a\b\c.h"
#include <ref\six\eight.h>
#include "123\456/789.h"
#include "bye.h"
'''
new_text = re.findall(r'\w+\.\w' ,text)
print new_text #list
print '\n'.join(new_text) #string
print set(new_text) #No duplicate
"""Output-->
['hello.h', 'hello.h', 'hello.h', 'hello.h', 'hello.h', 'c.h', 'eight.h', '789.h', 'bye.h']
hello.h
hello.h
hello.h
hello.h
hello.h
c.h
eight.h
789.h
bye.h
set(['eight.h', '789.h', 'hello.h', 'c.h', 'bye.h'])
"""
Should I use rename or soemthing?
Yes you can try this.
import os
import fnmatch
for i,fn in enumerate(os.listdir("C:/Bilder")):
if fnmatch.fnmatch(fn, 'IMG*'):
os.rename(os.path.join('C:/Bilder', fn), os.path.join('C:/Bilder','Bilde%d.jpg' % i))
What is the full name,and what should the new full name be?,you most explain better.
IMG.jpg to HH.jpg?
HH1.jpg HH2.jpg....?
import os
os.chdir('D:/Python24/pyasn1')
python setup.py install
This is wrong.
Do you know what cmd is?
http://www.bleepingcomputer.com/tutorials/tutorial76.html
When you have unpacked files you need to navigate to that folder in cmd.
Then use python setup.py install
.
This is one way.
The other are using setuptools as postet before.
It took my 15sek to install pysnmp with setuptools.
This is also done in cmd and not in IDLE easy_install pysnmp
#!/usr/bin/env python
This is only for linux,on windows you dont need that line.
Can you post the script,so shall i test it in py2exe and cxfreeze.
humansize.py from the >>> prompt in the shell (interactive IDLE). How do I do that?
You dont do that because it wrong.
To run a script.
From cmd python humansize.py
or as posted by tony by using File->new window then F5(run)
.
If you want to use humansize.py in IDLE you have to import it.
How to import and using a script look at this post.
http://www.daniweb.com/forums/thread322120.html
A good editor like pyscripter make it easy,it has run button.
http://code.google.com/p/pyscripter/
From CMD. easy_install pysnmp
.
To do this you need to install Setuptools
Or as Gribouillis posted from CMD navigate to folder for unpack files and write python setup.py install
>>> import pysnmp
>>> dir(pysnmp)
['__builtins__',
'__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__path__',
'majorVersionId',
'version']
>>> pysnmp.version
(4, 1, 15)
>>>
You can use Pickle
import pickle
import numpy
X = numpy.matrix(numpy.zeros([801,801]))
print 'Before pickle'
print '-'*30
print X
print '-'*30
def write(data, outfile):
f = open(outfile, "w+b")
pickle.dump(data, f)
f.close()
def read(filename):
f = open(filename)
data = pickle.load(f)
f.close()
return data
if __name__ == "__main__":
some_data = X
write(some_data, "temp.file")
read_data = read("temp.file")
print 'After pickle'
print '-'*30
print read_data
print '-'*30
"""Output-->
Before pickle
------------------------------
[[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]]
------------------------------
After pickle
------------------------------
[[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
...,
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]
[ 0. 0. 0. ..., 0. 0. 0.]]
------------------------------
"""
>>> l = ['asd',"asd'das",'qw','213']
>>> l
['asd', "asd'das", 'qw', '213']
>>> l.pop(0)
'asd'
>>> l
["asd'das", 'qw', '213']
>>> l.pop(1)
'qw'
>>> l
["asd'das", '213']
>>>
This is what`s happens.
l.pop(0) take out take out 'asd'
Then "asd'das" take place as element 0
Next when you use l.pop(1) it will take our element 1 'qw'
Maybe you get confused that "asd'das" is one element in the list.
You are looking for random.shuffle().
To see all method under random module use dir(random)
For help use help(random.shuffle)
>>> random_name = ['Mohamed', 'Ahmed','Aboubakr']
>>> random.shuffle(random_name)
>>> random_name
['Mohamed', 'Aboubakr', 'Ahmed']
>>> random.shuffle(random_name)
>>> random_name
['Ahmed', 'Mohamed', 'Aboubakr']
>>> random.shuffle(random_name)
>>> random_name
['Ahmed', 'Aboubakr', 'Mohamed']
>>>
You can also use re to remove all characters with the W flag.
Just to give a little more info about this.
richieking is talking about regular expression.
http://docs.python.org/library/re.html
Her is a demo of how it work.
Using findall is an easy option,search and match are to other option to read about.
>>> import re
>>> r = re.findall(r'\W', 'test.. hi? for ,,,')
>>> r
['.', '.', ' ', '?', ' ', ' ', ',', ',', ',']
>>> #Make it a string
>>> ''.join(r)
'.. ? ,,,'
>>>
A little help.
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>>
In this code i exclude string.ascii_letters
import string
exclude = string.ascii_letters
s = 'test.. hi? for ,,,'
punc_text = ''.join(ch for ch in s if ch not in exclude)
print punc_text #.. ? ,,,
I keep getting an error message saying raw_input isn't defined?
If you are using python 3 change raw_input() to input()
a.remove(p) will never work because string method dos not have a remove method.
Some tips about your code GDICommander's
Dont use "file" as an variable name,it`s a reseverd keyword for python.
You dont need "import string" to use split.
So it could look like this,wihout \r\n
my_file = open("example.csv", "rb")
for line in my_file:
l = [i.strip() for i in line.split(',')]
print l
Any idea how to change the format to something like this?
You can use the new string formatting has a lot of powerful features an was new in python 2.6
http://docs.python.org/library/string.html#formatstrings
An example.
google = {
'facebook.com': 230,
'yahoo.com': 9,
'fifa.org': 67,
'msn.com': 3}
print 'google.com'
for name in sorted(google):
print("\t\t{name:11}{score:>10.4f}".format(name=name, score=google[name]))
"""Out-->
google.com
facebook.com 230.0000
fifa.org 67.0000
msn.com 3.0000
yahoo.com 9.0000
"""
i m using python 2.5 ,i m getting error in the first line(i.e,with open line)
Why are using an so old version as 2.5?.
I shall test later on my laptop there i have 2.5 and see if it work.
The with statement did come with the release of python 2.5.
http://docs.python.org/whatsnew/2.5.html#pep-343-the-with-statement
You can try to add this as first line.
from __future__ import with_statement
Write this in IDLE.
>>> import sys
>>> sys.path
The list you get is where python look for .py files,when you are using a import statment.
http://docs.python.org/tutorial/modules.html#the-module-search-path
Dont use bold character for everthing.
Here is and example you can look at and try out.
#average.py
#saved in python dir
from __future__ import division
def average(seq_in):
if isinstance(seq_in, (list, tuple)):
return sum(seq_in) / len(seq_in)
else:
return 'Input can only be list or tuple'
So we save this as average.py in python folder(or a python path folder so python can find it)
Import and test it out before we use it in new script.
>>> from average import average
>>> average
<function average at 0x04D2C430>
>>> average([1,2,3,4])
2.5
>>> average(88)
'Input can only be list or tuple'
>>> average('hi')
'Input can only be list or tuple'
>>>
It work as it should.
Then we can use it in a new code like this.
from average import average
def calc_average(l):
return average(l) #Here we use the imported code
def radius_2():
'''Not finish yet'''
pass
def main():
'''Main menu'''
while True:
print '(1) Calculate average'
print '(2) Calculate radius'
print '(Q) Quit'
choice = raw_input('Enter your choice: ')
if choice == '1':
user_in = raw_input('Enter numbers for average calculation: ')
a = [float(i) for i in user_in]
print calc_average(a)
elif choice == '2':
radius_2()
elif choice in ['Q','q']:
return False
else:
print 'Not a correct choice:', choice
if __name__ == '__main__':
main()
Use code tag,are you using python 3?
Then you have to change print statement,because as mention many times print is a function in python 3.
#python 3
"""
file_1.txt-->
99 root S 5176 95 41.2 8.3 snmpd
file_2.txt-->
99 root S 5176 95 1.0 8.3 snmpd
"""
with open('file_1.txt') as file_1:
with open('file_2.txt') as file_2:
f1 = [float(item.split()[5]) for item in file_1]
f2 = [float(item.split()[5]) for item in file_2]
print (f1[0] - f2[0]) # 40.2
with open(('file2.txt') as file_1):
That is not my code,you can just copy it.
Now you have made 3 error in that short line.
Just compare then you should see it.
Another way to do this.
"""
file_1.txt-->
99 root S 5176 95 41.2 8.3 snmpd
file_2.txt-->
99 root S 5176 95 1.0 8.3 snmpd
"""
with open('file_1.txt') as file_1, open('file_2.txt') as file_2:
f1 = [float(item.split()[5]) for item in file_1]
f2 = [float(item.split()[5]) for item in file_2]
print f1[0] - f2[0] #40.2
Try this.
import urllib.request
page = urllib.request.urlopen("http://www.randompickupline.com/")
text = page.read().decode("utf8")
where = text.find('<p id="pickupline">')
start_of_line = where + 19
end_of_line = start_of_line + 150
line = (text[start_of_line:end_of_line])
pick_text = line.find('</p>')
print (line[:pick_text])
"""Out-->
Do I know you? (No.) That's a shame, I'd sure like to.
"""
When it comes to parse website,using a good parser like BeautifulSoup or lxml can make it eaiser.
Here is an example that do what you want,this is for python 2.x
from BeautifulSoup import BeautifulSoup
import urllib2
url = urllib2.urlopen("http://www.randompickupline.com/")
soup = BeautifulSoup(url)
tag = soup.find("p", {"id": "pickupline"})
print tag.text
"""Out-->
It's dark in here. Wait! It's because all of the light is shining on you.
"""
A print statement should clear it up.
Here first line get run,where user input return an integer.
Then that integer is passed inn as an agument to function adder.
Then d take that value and put result in a new variable d.
Then we print out result.
Because of bad name to variables,this get more confusing than it should be.
x = int(raw_input('enter any number :'))
def adder(d):
d = d + 1
print d
adder(x)
Log in that use Javascript make the process a lot harder.
Read Embedded script is messing up my web-scraping
You have Spidermonkey
"Execute arbitrary JavaScript code from Python.
Allows you to reference arbitrary Python objects and functions in the JavaScript VM"
Look at PyPi for tool that can help.
i agree with the splicing which i've found helpful.
"splicing" is that a secret python slicing method,just kidding :icon_wink:
"splicing" in action.
>>> s = 'hello'
>>> s[::-1][-1]
'h'
>>>
If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position.
l.insert(newindex, l.pop(oldindex))
>>> l = [[5,5,5],[5,5,5,5,5],[]]
>>> l.insert(1, l.pop(2))
>>> l
[[5, 5, 5], [], [5, 5, 5, 5, 5]]
>>>
Rember use code tag.
data1 = []
x_org = []
locx = open('test.txt', 'w')
for i in range(9):
x_org.append(i)
locx.write('\n'.join([str(i) for i in x_org]))
locx.close()
Can break it up it little so it`s easier to understand.
>>> l = [1, 2, 3, 4, 5, 6, 7, 8]
>>> #We have a list of integer,we much convert into string
>>> #With python List Comprehensions
>>> [str(i) for i in l]
['1', '2', '3', '4', '5', '6', '7', '8']
>>> #Or in a functional style with map
>>> map(str, l)
['1', '2', '3', '4', '5', '6', '7', '8']
>>> #Then join it into a string with \n(new line character)
>>> '\n'.join([str(i) for i in l])
'1\n2\n3\n4\n5\n6\n7\n8'
>>> '\n'.join(map(str, l))
'1\n2\n3\n4\n5\n6\n7\n8'
>>>
locx = open('C:\Temp\Loc', 'w')
Use C:/Temp/test.txt or C:\\Temp\\test.txt and you need a file name loc.txt?
\ Can be used as an Escape Characters an file will not be found.
but i m not getting output...wen i run a program it is showing error .
Then you have to post the error we are not mind reader.
The code from -ordi- works fine,and with is a good thing to use because it close() file auto.
If you use python 3 change the print statement.
#Works python 3 and 2
with open ("test.txt") as sis:
for line in sis:
split_line = line.strip().split()
print ("%s %s" % (split_line[0], split_line[3]))
A one liner for fun.
print '\n'.join([i[:2]+i[8:11] for i in open('test.txt')])
'''Out-->
a1 a4
b1 b4
c1 c4
d1 d4
'''
Like this and it should work.
from __future__ import division
choice =1
while choice==1:
print "1. Celcius to Ferenheit"
print "2. Ferenheit to celsius"
print "3. Escape"
ham=input("Please select an option: ")
if ham==1:
tc=input("Put a celcius temp in: ")
tf=(9/5)*(tc+32)
print tf
if ham==2:
TF=input("Enter a Farenheit temp: ")
TC=(5/9)*(TF-32)
print TC
if ham==3:
choice=0
As first line use this and it will work.
from __future__ import division
Or.
TF = float(raw_input("Enter a Farenheit temp: "))
TC = (5/9.0)*(TF-32) #9.0 make it float
Read this.
http://www.ferg.org/projects/python_gotchas.html#contents_item_3
The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code.
Use list as i have canged in your code.
sum(list/tuple) not list/tuple.sum.
#The normal way off making list/array in python
homescore = []
visitingscore = []
for x in range(2):
home = int(raw_input('The home team score this inning. '))
homescore.append(home)
for x in range(2):
visiter = int(raw_input('The visiting team score this inning. '))
visitingscore.append(visiter)
print 'The Home team score is ', sum(homescore)
print 'The Visiters team score is %d ' % sum(visitingscore) #with string formatting
if sum(homescore) > sum(visitingscore):
print"The Home team wins!"
else:
print"The visiting team wins!"
With pywinauto sending the source code html to notepad,not that i understand why you need this.
Just copy and paste into notepad will be my easy answer for this.
With a bigger website i guess sending to much text to notepad will break,or you have to break up source code.
import urllib
from pywinauto import application
url = urllib.urlopen("http://beans.itcarlow.ie/prices.html")
Source = url.read()
app = application.Application()
app.start('notepad')
app.notepad.edit.TypeKeys(Source)
Maybe read my post better woooee it has has the same link :)
It tok my 5sek to display result in notepad ctrl-c and ctrl-v.
So to the question why to you need to display source code in notepad?
Just to show you one normal to take out som info from a website.
from BeautifulSoup import BeautifulSoup
import urllib
url = urllib.urlopen('http://beans.itcarlow.ie/prices.html')
soup = BeautifulSoup(url)
print soup #site conteds,this is the source code no need to display it in notepad.
tag = soup.findAll('strong')
print tag[0].text #$6.36 ##We have taken out price of bean from website
Cgi script is limited and if we compare something like jboss,to same in python it will be one of the many Webframework for python.
Django is the most known.
Some sites that run on django.
http://www.djangosites.org/
web2py is also very simpel to setup,and is has a lot power.
http://www.youtube.com/watch?v=53DF4pkeriU
Like this no need to use time or decimal module.
Set upp notepad++ correct or use a good ide editor for python like pyscripter or pydev/SPE IDE
http://code.google.com/p/pyscripter/
http://pythonide.blogspot.com/
http://pydev.org/
hours = float(raw_input("Enter Hours Worked: "))
gross = hours * 12
netpay = gross - (gross * 0.15)
print "Your net wage is %.2f " % netpay
The code dos what you want it stop for user_input,and print out answer with 2 decimal places.
If it dos not,notepad++ is the problem.
http://www.daniweb.com/forums/thread151270.html
http://cse.ucdavis.edu/~chaos/courses/nlp/Software/Windows/npp.html
richieking this was an 5 years old post.
As Gribouillis posted python has never break anything before release of python 3.
Python 3 has been planned for many years,and is of course the right descion for the evolution of this great language.
But the are very clear that python 2 will for most pepole be the best choice for some years more.
If you look at tiobe over the last 10years rating there are not many languages that has an posetive evolution,python has is one of the few the languages that has an posetive curve.
But we are not in a hurry. Soo many versions for what?
It`s of course to get new features out,and fix some bugs.
If you dont like it just stay with an older version.
I have every version from 2.5 to 3.2 installed on my laptop,that one way to test things out,and stability has never been an issue.
Dont make a mistake. yea... python is not ubuntu but at least the idea of stabilty for a software, system, tool etc are the same.
Long live the snake!!!!!
ubuntu has nothing to do with python stabilty,python has been and are stable on all platform.
And bugs are taken serious in python,look at bug report in python.
Like this for python 3,there has been big changes in urllib for python 3(urllib + urllib2 joined together)
But i guess you havent used python 2,so the changes dosen`t matter for you.
or is there a way to convert a .html file into a .txt file?
The code under you get source kode(html),that is now just a string(text).
You can not convert it to txt,you can save it as txt(but what is the point of that)
One example of what you can to:
when you have read in source code(html) you can du stuff like parse out info you want,with good pareser like beautifulsoup and lxml.
Or just use python string tools like find,slice.split... to take out info you need.
#python 3
import urllib.request
page = urllib.request.urlopen('http://homepage.mac.com/s_lott/books/index.html')
text = page.read().decode("utf8")
print(text)
The same in python 2.x
#python 2.x
import urllib
page = urllib.urlopen('http://diveintopython3.org/').read()
print page