880 Posted Topics
Re: codeList = root.findall(".//ScanCodes/ScanCode/Code") print codeList What dos "print codelist" output. So here as a demo i use find() to find "value" and "text" in [1]: xml = '''\ <foo> <bar key="value">text</bar> </foo>''' In [2]: import xml.etree.ElementTree as ET In [3]: xml = ET.fromstring(xml) In [4]: xml.find('./bar').attrib['key'] Out[4]: 'value' In [5]: … | |
Re: Why lambda expression? It can make code less readable. > All you should need to do is import string and apply in to your string's first character, and string.digits, and you should be able to use that as the lambda expression. I agree,but there is no need to `import string`. … | |
Re: [MySQLdb](https://pypi.python.org/pypi/MySQL-python/1.2.5) or [PyMySQL](https://github.com/PyMySQL/PyMySQL) | |
Re: Post link and what you what out. | |
Re: > it does for the files but i jsut got told they arent files but subfolders that have the numbers in the names which makes this so much more confussing for me. Use `os.walk()` it recursive scan all folder and subfolders. Example. import os import re search_pattern = r'\d' target_path … | |
Re: You really shouldn't be be using CGI. Did you read me answer in you other [post](http://www.daniweb.com/software-development/python/threads/481910/python-and-localhost)? You never call calc function,line 18 i think should be inside calc function. To get the error you get both listprice and discountpercent most be None. >>> listprice = 100 >>> discountpercent = 80 … | |
Re: I think Gribouillis has postet some about unicode in Python 3 in your previous posts. Can take a little more about this,for unicode was a big change in Python 3. If you get a `UnicodeDecodeError` it most likely means that you’re not reading the file in the correct encoding. You … | |
Re: Cgi is pretty much dead in Python,and that's is very posetive. Python community did make an all Python soution [PEP 3333](http://legacy.python.org/dev/peps/pep-3333/) So this is called [WSGI](http://wsgi.readthedocs.org/en/latest/)(Web Server Gateway Interface),and is much better than cgi. For small task like this is [Flask](http://flask.pocoo.org/) and [Bottle](http://bottlepy.org/docs/dev/index.html) perfect. | |
Re: Stefan stop post your code in 8 years old `Code Snippets` post. Yes Python has moved on,and your soultion is not better at all. >>> from collections import Counter >>> Counter('Her goes your text text'.lower().split()) Counter({'text': 2, 'goes': 1, 'her': 1, 'your': 1}) | |
Re: Re upload your code with working indentation. | |
Re: Start by testing stuff out in interactive interpreter. >>> lst = ['This', 'is' 'some', 'test', 'of', 'someting'] >>> lst[0] 'This' >>> len(lst[0]) 4 So useful for finding 4 letters word. Basic iterate over a list. >>> lst = ['This', 'is', 'some', 'test', 'of', 'someting'] >>> for item in lst: ... … | |
Re: Do you mean download a file in chunk(spilt it up) so it dos not use so much memory? Something like a do in this [post](http://www.daniweb.com/software-development/python/threads/478404/parse-large-one-line-text-file#post2089945). | |
Re: > And there you go, you just mentioned another way of solving the problem. There are several ways to the market in this case. Yes there are severals ways,i was also thinking about regex,but split and startswith works just fine in this simple case. And may even be better than … | |
Re: I get a count of 4 with conted in your last post,i save your content as *UTF-8* and read it in same way. #Python 2.7 import codecs with codecs.open('test_hindi.txt', encoding='utf-8') as f: contend = f.read() word_cont = contend.count(u'\u092a\u0930') print contend print '-' * 30 print repr(contend) print '-' * 30 … | |
Re: > pyinstaller to make an executable, wouldn't that eliminate the need for the python to be installed on the system? Yes and there are more [tool](http://docs.python-guide.org/en/latest/shipping/freezing/),a GUI [tool](https://code.google.com/p/gui2exe/) for many freezing tool. [Nukita](http://nuitka.net/) and also Cython can make "exe",a new approach [pynsist](http://pynsist.readthedocs.org/en/latest/) See video from pycon 2014, [The Day of … | |
Re: Import is. >>> import xml.etree.ElementTree as ET >>> ET.VERSION '1.3.0' And you should not name file `elementtree.py`,it shall not be in desktop folder. This is a file in Pyhon library. For me only [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) or [lxml]( http://lxml.de/) for parsing. | |
Re: The error message is very clear,Python can not find "sample.txt" in that path. with open('C:/Users/jolie_tia/Documents/sample.txt') as f: print f.name '''Output--> Message File Name Line Position Traceback <module> <module4> 1 IOError: [Errno 2] No such file or directory: 'C:/Users/jolie_tia/Documents/sample.txt' ''' Here i fixing the error by making folders for that path … | |
Re: You have convert all input to integers,so answer(ans) is also an integer. Can look at some improvement. num1 = int(raw_input("Enter an integer")) num2 = int(raw_input("Enter a second integer")) num3 = int(raw_input("Enter a third integer")) print "The sum of the 3 integers entered is: {}".format(sum((num1, num2, num3))) So in this version … | |
Re: Slice it out can be another option. with open('06 Rooster.mp3', 'rb') as f: f.seek(-128,2) tag_content = f.read(128) title = tag_content[3:33] print title # Rooster You do know that there are several libraries that can do this(Mutagen,eyeD3...)? import eyed3 audiofile = eyed3.load("06 Rooster.mp3") print audiofile.tag.title print audiofile.tag.artist print audiofile.info.bit_rate_str '''Output--> Rooster … | |
Re: def lst_corrector(lst, index_vaule): value_change = raw_input('Enter correct value: ') for index, item in enumerate(lst): if index == index_to_change: lst[index] = value_change return lst #Error should be car lst = ['boat', 'train', 'carfd'] index_to_change = 2 print lst_corrector(lst, index_to_change) #--> ['boat', 'train', 'car'] | |
Re: Dont use `list` and `dict` as variable names,words are reseverd bye Python. To clean it up. my_file = open("words.txt") lst = [] #Outside the loop for word in my_file: word = word.strip() lst.append(word) my_file.close() #searching for the word in list search_word = "fox" if search_word in lst: print 'Word found: … | |
Re: > I have tried a written a code like so re.findall(r'[A-Z]{3}[a-z][A-Z]{3}',string) to find the solution for this python challenge Add [^A-Z] in each end. [^A-Z] # any character except a capital letter [^A-Z] # ensures that there isn't a 4th uppercase letter And parentes () around [a-z],so it's a capturing … | |
Re: Hint. >>> import re >>> data = '''(*^+*]$]+@+*_##)&)^(@$^]e@][#&)(''' >>> re.findall(r'[a-z]', data) ['e'] | |
Re: Take a look at [Click](http://click.pocoo.org/) from the creator of [Flask](http://flask.pocoo.org/) Armin Ronacher. | |
Re: I give it a try for fun. #multi_glob.py from glob import glob import os def multi_glob(path=None, *args): '''glob that can handle multiple file extensions option. #--- Usage ---# from multi_glob import multi_glob multi_glob(folder_path, '*.py', '*.txt') ''' try: os.chdir(path) except OSError: os.chdir(os.getcwd()) print 'Wrong path using script(.py) folder path' f_lst = … | |
Re: Microframework like [Flask](http://flask.pocoo.org/) and [Bottle](http://bottlepy.org/docs/dev/index.html) would be fine for a task like this. There are many [14 Minimal Web Frameworks for Python](http://codecondo.com/14-minimal-web-frameworks-for-python/) > (mayby web2py) Would also be ok. > or should I just dive into HTML/CSS? You should look in to it hard to do web stuff without it,also … | |
Re: > Is wxPython still around? Yes still alive. Lastet officale oppdate is(25-Dec-2013) wxPython (classic) 3.0.0.0 It will soon be ready for Python 3,work is going on [Project Phoenix](http://wiki.wxpython.org/ProjectPhoenix) Work well for Python 3,to test it out look [here](http://wxpython.org/Phoenix/snapshot-builds/) | |
Re: One way. f_object = open('filename', 'rb') while True: chunk = f_object.read(180) if not chunk: break do_something_with(chunk) f_object.close() More modern an pythonic. from functools import partial with open('filename', 'rb') as f_object: for byte in iter(partial(f_object.read, 180), b''): # Do stuff with byte | |
Re: [Pyscripter](http://code.google.com/p/pyscripter/) as mention is great(windows only) I will also mention [Spyder 2](http://code.google.com/p/spyderlib/) and [Pydev](http://pydev.org/) | |
Re: Same after "d" missing comma. Learn to use string formatting. >>> a = 100 >>> difference = 'high' >>> print('The gap between {} and 1000000 is {}'.format(a, difference)) The gap between 100 and 1000000 is high http://ebeab.com/2012/10/10/python-string-format/ A good Python editor will spot error like this for you. [Pycharm](http://www.jetbrains.com/pycharm/) has … | |
Re: > I was thinking that if a <title> has no corresponding <pos>, delete that title, but I don't know how to do that. Can anyone suggest a solution? Some hint use `fetchNextSiblings()` if return empty list,then `decompose()` that title tag. xml = '''\ <page> <title>dasher</title> <pos>red</pos> </page> <page> <title>dancer</title> <pos>red</pos> … | |
Re: Good effort Peter 18,the code dos what it shall. I would suggest some improvements. To strip off `\n` is better to use `strip()` >>> s = 'hello\n' >>> s.strip() 'hello' So code under can be one line `matchf = [i.strip() for i in dllmatch]` matchf = dllmatch.readlines() for i in … | |
Re: One way,you may need to break it up if list comprehension are something new. List comprehension is very common to use in Python. with open('number.txt') as f: lst = [i.strip() for i in f] print lst print [float(i.split('$')[1]) for i in lst] #split out $ and make float print sum(float(i.split('$')[1]) … | |
Re: Some hint,using a parser in standard library [ElementTree](https://docs.python.org/2/library/xml.etree.elementtree.html). Most of the time i use BeautifulSoup or lxml for parsing. import os import xml.etree.ElementTree as ET tree = ET.parse("test.xml") root = tree.getroot() for element in root.iter('Path'): print element.text print os.path.basename(element.text) '''Output--> C:\Windows\system32\Riched32.dll Riched32.dll C:\Windows\system32\napinsp.dll napinsp.dll ''' > But not duplicated .dll … | |
Re: `[::-1]` or `reversed()` >>> s = 'hello' >>> s[::-1].upper() 'OLLEH' >>> ''.join(reversed(s.upper())) 'OLLEH' | |
![]() | Re: url is set to None,then you get this error message. >>> url = 'http://www.google.com' >>> url[0:4] 'http' >>> url = None >>> url[0:4] Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: 'NoneType' object has no attribute '__getitem__' A tips is to just use print on … |
Re: >>> lst = [[1,2,3], [4,5,6]] >>> del lst[1] >>> lst [[1, 2, 3]] >>> lst = [[1,2,3], [4,5,6]] >>> lst.remove(lst[1]) >>> lst [[1, 2, 3]] >>> lst = [[1,2,3], [4,5,6]] >>> lst.pop(1) [4, 5, 6] >>> lst [[1, 2, 3]] | |
Re: Komodo Edit there is a little more stuggle to setup run button. http://community.activestate.com/forum-topic/executing-python-code-within-komodo-edit Komodo IDE has run button build in,because it has debugging features for python build in. Look at [Pyscripter](http://code.google.com/p/pyscripter/)(windows only) and [Spyder](http://code.google.com/p/spyderlib/) great editors for python. Can also mention [Pydev](http://pydev.org/) wish is powerful,not as lightweigt need of course … | |
Re: There are some room for improvement in this code. In line 14 you are removing punctuation,then in line 20 you are testing for punctuation that's already removed. There is no need to use a file and append word,just use `set()`. So then it could look like this. import string with … | |
Re: Here is a differnt way,with a little change of good answer given by pyTony. Using `next()` to skip first line(header). def files_to_one(new_file, *files): with open(new_file, 'w') as fout: for f in (files): with open(f) as fin: next(fin) for line in fin: fout.write(line+'\n') | |
Re: Some hint. >>> s = ['06', '15', '26', '34', '36', '-', '16'] >>> t = ['16', '24', '30', '34', '43', '-', '20'] >>> s[0] '06' >>> t[0] '16' >>> s[0] == t[0] False >>> s[3] == t[3] True >>> s[5] == t[5] True > But I dont know why it … | |
Re: > .I have not come across the curly brackets yet on this line of code New string formatting came out in Python 2.6 Gribouillis has much about it [here](http://www.daniweb.com/software-development/python/code/232375/string-formatting-specifications) A quick look at at old and new. >>> old = 'My name is %s' % 'foshan' >>> old 'My name … | |
Re: [QUOTE]isnt this the shortest method[/QUOTE] Not when you post [B]C[/B] code in python forum. [CODE]>>> raw_input('enter a number: ')[::-1] enter a number: 1234 '4321' [/CODE] | |
Re: > I need it for a code such as this: No that just stupid code. Explain better what you want do,then you get suggestions for better ways to solve it. | |
Re: > And is there any other/better way to scrape particular data ? There is a better way,and HTML and regex is not the best way. Read bobince funny and good answer [her](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Python has two star paser [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/) and [lxml](http://lxml.de/) A couple of example parsing a <strong> tag. from … | |
Re: Sorry but the code is not good at all. Now you have a while True loop start at line 14 with a lot of code in it. You have to use function or class when code get longer. Look at code in first part [here](http://www.daniweb.com/software-development/python/threads/20774/starting-python) See how function `get_name() show_name() … | |
Re: > if we want to convert 'xyz' to uppercase, why dont we enter the argument inside the function Because `uppercase()` is a method that belong to string class and only works on strings. The [Built-in Functions](http://docs.python.org/2/library/functions.html) work on many class/objects. Let's see how `len()` work on string and list. >>> … | |
Re: Good idèe bye slate to update objects namespace. You can also just work with dictionary if you need result `variable2 + variable3` wish is `30`. Herer a little compressed version. >>> s = 'variable1=5&varible2=3&variable3=27&varible4=1' >>> d = dict((k[0], k[1]) for k in [i.split('=') for i in s.split('&')]) >>> int(d['varible2']) + … | |
Re: That way is a little unpythonic way to do it rrashkin. d = {'Seven': 22, 'Six': 0, 'Three': 35, 'Two': 0, 'Four': 45, 'Five': 34, 'Eight': 0} for k,v in d.items(): if v == 0: del d[k] print d #--> {'Five': 34, 'Four': 45, 'One': 10, 'Seven': 22, 'Three': 35} … | |
Re: > returns the last line of that txt file and not the first (as I need). If you just need first line why make it more difficult than it is. just `readline()` give back first line. If need line by line drop `while 1` and just iterate over lines with … |
The End.