- Strength to Increase Rep
- +8
- Strength to Decrease Rep
- -2
- Upvotes Received
- 26
- Posts with Upvotes
- 23
- Upvoting Members
- 16
- Downvotes Received
- 1
- Posts with Downvotes
- 1
- Downvoting Members
- 1
133 Posted Topics
Re: [QUOTE=RMartins;537916]but how can i prove for example that the result of sqrt(n) is an integer?[/QUOTE] You can do this (maybe is there more elegant way) [CODE] if math.sqrt(n) == float(int(math.sqrt(n))): print "sqrt(n) is an integer" [/CODE] | |
Re: [CODE] import csv reader = csv.reader(open("c:\sample.dat")) d={} for row in reader: d[row[0]]=row[1:] [/CODE] | |
Re: Just a quick point. To turn an object into string, you can define the special method __repr__ in your object : [CODE] class myobject: def __init__(self, name): self.name=name def __repr__(self): return "my name is %s" % (self.name) o=myobject("toto") print o > toto [/CODE] | |
Re: I'd write [CODE] self.cursor.execute("INSERT INTO DatabaseName (C1, C2, C3, C4, C5) SELECT (C1, C2, C3, C4, C5) FROM DatabaseName WHERE C1='%s'", [newC1Value]) [/CODE] | |
Re: [QUOTE=sys73r;1691325]my bad, the code i got is: input.csv 1,2,text, date, qwertyuiopasdfghjklñzxcvbnm, yhnujmik,2121212121 [CODE]import csv reader = csv.reader(open('input.csv', 'rb'), delimiter=',',quoting=csv.QUOTE_NONNUMERIC)) csv_out = csv.writer(open('output.csv', 'w')) for row in reader: content = row[0] + row[1] + row[5] + row[6] csv_out.writerow( content )[/CODE] which is giving me: 1,2,y,h,n,u,j,m,i,k,2,1,2,1,2,1,2,1,2,1 instead of 1,2,yhnujmik,2121212121 thanks![/QUOTE] Ok with … | |
Re: This code goes recursively in all the sudirs of your rootdir. Open all the files, read the lines, calls a function to process your line (here, it does nothing) and overwrite your files with your new lines [code=python] import os rootdir='c:\Your\Path' def doWhatYouWant(line): return line for subdir, dirs, files in … | |
Re: Another method [CODE] import fnmatch pattern = '*.rtf' files = ['doc.txt', 'stuff.rtf', 'artfunction.exe', 'rtfunc.bat', 'doc2.rtf'] print('\n'.join(filename for filename in fnmatch.filter(files, pattern))) [/CODE] | |
Re: A classical method using list comprehensions [CODE] dict([(list[i], list[i+1]) for i in range(0, len(list), 2)]) [/CODE] function dict takes a list of tuples for arguments and uses the first term of the tuple as key and the second as value If you need more explanations, don't hesitate to ask. | |
Re: you have to do [code] folder = r'\\192.168.0.12\myshare1' # OR folder = '\\\\192.168.0.12\\myshare1' [/code] | |
Re: Something like this : [CODE] import random class TV(object): def __init__(self): # self refers to the object itself # Don't mix up an object instance and an object class. # Class is the definition of a type of object (for example TVs all have a brand and channels) # instance … | |
Re: Here are some function you can look at : - os.listdir(mydir) will list all the files from "mydir" - fnmatch.filter(files_list, "*.txt") will give you a list of all text files in the files_list (tip : fnmatch.filter(os.listdir(mydir)) - os.path.join(mydir, file) will give you the absolute name of the file - os.walk(mydir) … | |
Re: [CODE] import glob print "\n\n".join(["".join([l for l in open(inf).readlines()[:2]]) for inf in glob.glob("C:\\path\\to\\the\\dir\\*.txt")]) [/CODE] | |
Re: Hi, You can use () to make it work (if you really want a one liner)... [CODE] def l(): return (lambda ...)() [/CODE] [CODE] def l(): return (lambda x=input("Enter the text to be decrypted: "),y=int(input("Enter the shift amount: ")): print("The decrypted text is: "+"".join(list(map(lambda x: chr(ord(x)+y),x)))))() [/CODE] | |
Re: Can you put the code you use for writing the content of the chest (i suppose : chest.printChest()) and the datas that are written ? BTW, for this kind of thing, you should have a look at __repr__ function. | |
Re: [QUOTE=richieking;1491374][CODE]print(["/".join(date.split("-"))])[/CODE] 2011/03/03 from my htc phone ;)[/QUOTE] I'd rather do [CODE] date.replace('-','/') [/CODE] | |
Re: You can try this : [CODE] protein="GWEIQPYVWDECYRVFYEQLNEEHKKIFKGIFDCIRDNSAPNLATLVRVTTNHFTHEQAMMDAVKFSEVLPHKKMHRDFLEKLGGLSAPVDNHIKGTDFKYKGKAKNVDYCKEWLVL" pp="LLCCCCCCCCCCCCCCCCCCHHHHHHHHHHHHHHHHHCHHHHHHHHHHHHHHCCCCHHHHHHHCLLLCCCCCHHHHHHHHHHHHHHHHHHHCCCCCCCCCCCHHHHHHHHHHHHCCL" gor="cccccccccccchhhhhhhhhhhhhhhhhhhhhhhccccccccceeeeecccccchhhhhhhhhhhcccchhhhhhhhhhhhhccccccccccccccccccccccceeceeccceec" aber="CCCCCCCCCCCCHHHHHHHCCHHHCHHHHHHHHHHCCCCHHHHHHHHHHHCCCCCCHHHHHHHCCCCCCCHCCHHHHHHHHHHCCCCCCCCCCCCCCCCCCCCCCCCCHHHHHHHCC" print "".join([str(i / 10) for i in range(len(protein))]) print "".join([str(i) for i in range(len(protein))]) print protein print pp print gor print aber [/CODE] | |
Hello there, I'm trying to generate a open office text document with tables generated from a database with the lpod library. I'd like to set the width of the tables columns but i can't manage it. Here is my test code so far : [code] import lpod.document import lpod.table doc … | |
hi, I try to write a app to automatically re-organize my mails (thunderbird). The first thing I try is to re-create my folders tree, once for each year. So i need to read mbox files and rewrite them [CODE=python] import mailbox mbx=mailbox.mbox("./in_mbox") mbx.lock() of=open("out_mbox", "w") for k, m in mbx.iteritems(): … | |
Re: This should work (not tested) [CODE] of = open(my_out_filename, 'w') for line in open(my_in_filename,'r'): if 'STRING' in line or 'INTEGER' in line: of.write(line) of.close() [/CODE] | |
Re: You can generate csv files... For an easy csv management, there is a csv module [url]http://docs.python.org/library/csv.html[/url] | |
Re: Have a look at this : [URL="http://www.devshed.com/c/a/Python/Database-Programming-in-Python-Accessing-MySQL/"]http://www.devshed.com/c/a/Python/Database-Programming-in-Python-Accessing-MySQL/[/URL] Others here [url]http://www.devshed.com/googlecse.html?cx=partner-pub-6422417422167576%3A6n32xsl5si9&cof=FORID%3A11&ie=ISO-8859-1&q=mysql+python&sa.x=28&sa.y=9&sa=Search&siteurl=www.devshed.com%2Fc%2Fb%2FPython%2F#1333[/url] | |
Re: Your datas aren't in a csv format... For csv, here is a simple example to read and write datas [CODE] import csv # This class is to define another csv format if you need to class excel_french(csv.Dialect): delimiter=';' quotechar='"' doublequote=True skipinitialspace=False lineterminator='\n' quoting=csv.QUOTE_MINIMAL fic='yourfile.csv' outcsvfic='out.csv' csv.register_dialect('excel_french', excel_french) cr=csv.reader(open(fic,"r"), 'excel_french') # … | |
Re: don't forget that, in os.walk, if you remove a dir from "dirs", it's subtree won't be explored. So [code] for dirpath, dirs, files in os.walk(path): for d in dirs: if d.startswith('.'): dirs.remove(d) # d's subtree won't be explored for f in files: if not f.startswith('.'): process_file() [/code] | |
Re: A better way to deal with text files is rather with for loop : [code] of=open(myoutfilename, 'w') for line in open(myfilename,'r'): print line of.write(line.replace(' ', '\t')) of.close() ######### OR ############## # not sure the 2 with on the same line work (and i can't test it right now) # this … | |
Re: It's because your class isn't "tennisPro", it's "tennis" | |
Re: wherever you write : [code] something("%s") % one_variable [/code] write [code] something("%s" % one_variable) [/code] | |
Re: Just one thing. For line iterating, i find it is a bad idea to load the whole file in a list (using readlines()) except if you can't process it sequentially. This will consume memory for really nothing interesting... Python allows iterating directly on file lines : [CODE] for line in … | |
Re: Sorry but i don't understand what you want... Can you post your code ? part of your sql files ? How do you execute the content of your sql files ? What do you want to write in your logfile ? Your question in far too open for me to … | |
Re: Fast method, using sets : [CODE] lines=open(myfile,'r').readlines() uniquelines=set(lines) open(outfile,'w').writelines(uniquelines) [/CODE] which can be done in only one line : [CODE] open(outfile,'w').writelines(set(open(myfile,'r').readlines())) [/CODE] | |
Re: You can do a list of lists... [CODE] rows=[[],[],[]...] # you call a particular cell by doing rows[3][4] [/CODE] | |
Re: [quote=soulmazer;1188565] edit: Admins/moderators, how do you put a code tag in a reply without creating a code box?[/quote] Hou can put spaces after the opening or before the closing [ ] [code ] [/code ] | |
Re: Problem 1 (done with python 2.4) [CODE] # -*- coding: latin-1 -*- # The first line is important and must be consistant with your file encoding (maybe utf8) import string t=string.maketrans('à éèëêôöîïù', 'aeeeeooiiu') print "lévitèrent à l'ïstrùmen".translate(t) [/CODE] for python 3.1 [CODE] # -*- coding: latin-1 -*- t=str.maketrans('à éèëêôöîïù', 'aeeeeooiiu') print ("lévitèrent … | |
Re: Here is some kind of skeleton to copy your files (you'll have to adapt it but the principle is here) : [CODE] import os, fnmatch, shutil mydir="/path/to/my/dir/" for filename in fnmatch.filter(os.listdir(mydir),'*.py'): shutil.copy(filename, "anotherDir/new-%s" % filename) [/CODE] Note that if you want to explore the dir recursively, you can do: [CODE] … | |
Re: Your way is so complicated : [CODE] def fileCount(filename): txt=open(filename).read() linecount=len(txt.split("\n")) wordcount=len(txt.split()) charcount=len(txt.replace("\n","")) # if you don't want tou count the '\n' return (linecount, wordcount, charcount) [/CODE] | |
Re: You don't need to split and join... [CODE] datas = """US 9 15 13 37 GE 10 13 7 30 CA 14 7 5 26""".split("\n") for l in datas: print l.split(None,1)[1] # the 1 split argument will tell to split only once # Faster # you can also use lists … | |
Re: another alternative: [CODE] "-".join(DEVICE_IP.split(".")) [/CODE] | |
Re: Just translate what you think : [CODE] f = open('testread.txt') f1 = open('testread1.txt', 'a') doIHaveToCopyTheLine=False for line in f.readlines(): if 'this is the line i want to search' in line: doIHaveToCopyTheLine=True if doIHaveToCopyTheLine: f1.write(line) f1.close() f.close() [/CODE] | |
Re: I can see 2 solutions : [code=python] list1 = ["20100122 http google.com 200", "20100124 http hushmail.com 200", "20100123 http microsoft.com 404" ] list2 = ["google.com", "yahoo.com", "msn.com", "hotmail.com", "gmail.com"] # 1 for i, e1 in enumerate(list1): for e2 in list2: if e2 in e1: print ("line %d : %s" % … | |
Re: [CODE] score = score + scores(int) [/CODE] don't you mean [CODE] score = score + int(scores) [/CODE] | |
Re: Post your pseudo code, ask your question and we'll see... | |
Re: 2 more solutions using dict() [code] datas="""Avenue,Av Road,Rd South East,SE Terrace,Tce""".split("\n") # The shortest way : print dict([(l.split(",")[0], l.split(",")[1]) for l in datas]) # a more understandable way lst=[] for l in datas: sl=l.split(",") lst.append((sl[0], sl[1])) d=dict(lst) print d [/code] | |
Re: You problem is not clear to me : Why is ('1101','4') the correct output ? '1101' is in the second list... Why not ('4472', '4') or ('5419', '2') Are these tuples displayed if and only if the run id of the id in list 1 is greater than any run … | |
Re: [QUOTE=edy_sze;1127397] [CODE]def IntToNBytes(integer, n): while len(tmphex)<2*n: tmphex = '0'+tmphex [/CODE][/QUOTE] You should NOT do this. Adding characters to strings like this is very slow. You should use a list instead (eventually, if you need a string a the end, you can join it (''.join(mylist)) : [CODE] def IntToNBytes(integer, n): tmphex … | |
Re: [QUOTE=autobiography;1112150] [CODE]if x != int(x):[/CODE][/QUOTE] This will tell you whether x is an int or not but should raise a ValueError if x is a non digit string ('a' for example) and will be false is x is a digit string ('6' != 6) What you want to do is … | |
Re: This should do the trick [CODE]keywords=[word1,word2,wor3,word4] file1="/path/to/file1.txt" file2="/path/to/file2.txt" f2=open(file2).readlines() # I load the 2d file in a list to be able to change a line by another easily for l in open(file1): # no need to open the file and read it before. This will read the file line by … | |
Re: [QUOTE=tigrum;1006105]Hello, [CODE] c.execute("INSERT INTO a (first, last) VALUES (%s, %s), row") [/CODE] [/QUOTE] Your "row" is inside the sql statement as a string ! You can do [CODE] c.execute("INSERT INTO a (first, last) VALUES (%s, %s)" % row) [/CODE] | |
Re: You should use modules like pickle or marshal to serialize and load your datas [code=python] import pickle c=['Hondros', {'Equiped': [['none', [], 0], ['Rags', [0, 1, 0, 0], 1, 1], ['Mocassins', [0, 0, 1, 0], 1, 1], ['Gauntlets', [0, 0, 0, 1], 6, 5]], 'Equipment': [0, 1, 1, 1], 'Stats': {'AC': … | |
Re: You should run your program with pythonw. This can be done in your command line or by renaming your .py file .pyw | |
Re: You can have a look at this to have an idea of web programming in python [url]http://webpython.codepoint.net/[/url] and this [url]http://webpy.org/[/url] I've never done web programming in python because norm in my job is php so i had to learn php. And i find it much less pleasant to write. If … |
The End.