2,646 Posted Topics
Re: You can use the `re` module >>> import re >>> string = "hello world!" >>> result = re.sub(r'\s+', ' ', string) >>> print(result) hello world! Another way is to split and join >>> result = ' '.join(string.split()) >>> print(result) hello world! | |
Re: You should be able to do this using ssh and module paramiko. | |
Re: Don't catch an exception only to raise a new one unless you know what you are doing! It hides the original exception and prevents debugging. So you could replace line 24 above with a naked `raise` statement to see where the error occured. You can use the Command class from … | |
Re: Always post the traceback when you report such errors! If it is a SyntaxError, use `print("module {0}".format(key))`. Otherwise, the format() method could cause an error in some cases (unicode encoding, or use of a custom class). | |
Re: You could probably use a non blocking input with a call to select() like in this example (linux only): #!/usr/bin/env python # -*-coding: utf8-*- from __future__ import unicode_literals, print_function, division __doc__ = """ module: sandbox.pollinput - """ import select import sys import time def opt_input(): i, w, x = select.select([sys.stdin], … | |
Re: Well, it looks like class A(object): # <--- small 'c' def __init__(self): self.a = 4 # <--- a and b are instance variables (not class variables) self.b = 6 class B(A): def __init__(self): # <--- watch the number of underscores A.__init__(self) # <--- call parent class constructor explicitely #some code … | |
| |
This snippet defines a Print function which can be used with python 2.4, 2.5, 2.6 and 3.0 (for 3.0 this is just the built-in print function). It's interface is that of the python 3.0's print. It simplifies the task of writing transitional code which runs under python 2.5 and python … | |
Re: Use the subprocess module process = subprocess.Popen('Snes9x', shell = True) | |
Re: [QUOTE=ajipw;1193849]i'm a student and i want to create an electronic dictionary, can you help me?[/QUOTE] You should start your own thread instead of reviving an old one, and also tell us what you mean by 'create an electronic dictionary', which is not exactly the same thing as a python dictionary. | |
Re: The interpreter only obeys python's grammar which says that both sides of a comparison operator must be "or_expr"s (one of python's syntactic categories). An expression like `not ...` can not be considered an or_expr. With parenthesis, it becomes an "atom", which can be considered as an "or_expr". Grammar is a … | |
Re: The best solution to avoid circular imports. If A imports B, then B should not import A, or import from A (although python is very permissive and will tolerate almost everything). Here, main imports submodule and both use printa(). You can write printa() and num_values in a third module, and … | |
Re: Write code to read each file in sequence and print each line first. We want to see python code. | |
Re: The first way is to define `__getattr__()` class Bar(object): def __getattr__(self, attr): return getattr(self.foo, attr) You can add some conditions on attr to avoid unexpected calls class Bar(object): def __getattr__(self, attr): if some_condition(attr): return getattr(self.foo, attr) else: raise AttributeError(attr) Another way is to define methods by a loop, eg class … | |
Re: At line 8, python thinks that a variable `left` is used, which was not previously defined. You probably meant if partone == 'left': Here `'left'` is a constant string instead of a variable name. | |
Re: In wxpython, it's 4 lines of code mg =wx.lib.gestures.MouseGestures (our_panel, True , wx.MOUSE_BTN_LEFT) mg .SetGesturePen(wx.Colour(255 ,0 ,0 ), 2) mg .SetGesturesVisible(True) mg .AddGesture ('DR', our_method) I don't know the PyQT equivalent. | |
Re: The solution is to use lists loc = locals() pf_list = [loc["p%sf" % x] + float(loc["p%s" % x]) for x in "abcdefgh"] ps_list = ["%.2f" % val for val in pf_list] or dicts loc = locals() pf_dict= dict((x, loc["p%sf" % x] + float(loc["p%s" % x])) for x in "abcdefgh") ps_dict … | |
Re: `os.getenv('PATH')` is the sequence of folders where the operating system finds executable programs. `sys.path` is the sequence of folders where python finds importable modules. | |
Re: Use the format method #!/usr/bin/env python # -*-coding: utf8-*- from __future__ import unicode_literals, print_function, division template = str("""<Result Type="PkFilter" Name="{RowNum:0>2d}" Color="{Color}" Show="0" MinIntensity="0" IntensityThreshold="100" AbsIntens="0" LogScale="0" MinMass="{MinMass}" MaxMass="{MaxMass}" Integrate="1" UsePercentile="0" IntensityPercentile="0.95" FindMass="0" RelMass="1"></Result>""").replace("\n", " ") def result(RowNum, MinMass, MaxMass, Color=str("#0000ff")): return template.format( RowNum = int(RowNum), MinMass = repr(float(MinMass)), # repr … | |
Re: There is something strange in this code >>> 'easyhint' < 8 False You are comparing constant strings to integers. You probably meant something else. This needs to be corrected. | |
Re: You could use an xmlrpc server on the remote computer. See the standard library module xmlrpclib. | |
Re: Reindent your code, I think indention is lost near line 126. | |
Re: There is no *best way*, there are different ways >>> class A(object): ... def __init__(self): ... self.mydict = dict() # <-- a dict is added to every instance ... >>> a = A() >>> a.mydict["foo"] = "bar" >>> >>> class B(object): ... shareddict = dict() # <-- this dict can … | |
Re: Your tuple contains probably a list >>> D = dict() >>> t = ([0], 1) >>> D[t] = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' | |
Re: If it is a csv file, it would be easier to read with the csv module. You would select the first entry of each row to get the first name. Can you post a few rows of your file (with real names and addresses replaced by similar fancy data) ? | |
This small python script invokes the [Treeline](http://treeline.bellz.org/index.html) tree visualizer to display xml files in a pleasant way.  | |
Re: I'm not (yet) a specialist of web frameworks in python, but yes, one of the purposes of templating systems is to mix html code and python code. The main idea is to write html files containing python expressions and blocks of code with a special markup syntax. This file is … | |
Re: You could insert 0.0 when there is no data Resistance.append(tuple((float(x) if x.strip() else 0.0) for x in row[4:])) | |
Re: Add a function to filter users def _my_users(users): for user in users: try: if not all(cg == "default" for cg in users[user]["group"]): yield user except KeyError: pass my_users = list(_my_users(users)) for user in my_users: # ... etc | |
Re: I think [this howto](http://docs.python.org/2/howto/webservers.html) is a good starting point. | |
Re: If `n` is an integer, `n << 8` is equivalent to `n * (2**8)`. The `<<` operator is called the left shift operator. It comes from the binary representation of integers, for example 6 is represented as `110` in binary form, and `6 << 3` as `110000`. Other languages use … | |
Re: You don't really need to be fluent in C++, the program contains only a few function calls which you can find in the [pywin32 API](http://timgolden.me.uk/pywin32-docs/PyWin32.html), especially [here](http://timgolden.me.uk/pywin32-docs/win32file.html). I won't do it for you because the intricacies of windows are not particularly my cup of tea (I'm a linux geek). Also … | |
Re: Which cells do you you want to merge ? what is their content ? What should the merged cell contain ? | |
Re: Perhaps try [this decorator](http://pypi.python.org/pypi/wxAnyThread/). | |
Re: `csvfile = fileinput.input(glob.glob('*.txt'))` may work. | |
Re: You can remove lines 6 to 11 because `raw_input()` always return a `str` object. The string's content is not examined, if the user types `123`, the string `"123"` is returned. `.isalpha()` tests if _all_ the characters in the string are alphabetic, for example `"ps2pdf".isalpha()` returns `False`. Otherwise, *variable* is not … | |
Re: Read [this](http://effbot.org/tkinterbook/label.htm) and also [this](http://lmgtfy.com/?q=tkinter+label+widget) | |
Re: You can chek that the parent directory exists import os def is_probably_valid(thepath): head, tail = os.path.split(thepath) return os.path.isdir(head) The ultimate test is to create a file with this path (if it does not already exist). File creation may fail depending on the user's or folder's permission for example. | |
This snippet is easy: it defines an immutable wrapper around a sequence type (list, deque, etc) which allows a class, function or module to expose a read only version of a sequence to the outer world. A constant wrapper around mapping types could also be defined in a similar manner. | |
Re: You can use a boolean flag for elem in lstLine[1:]: with open(fname) as ifh: found = False for item in ifh: lstData = item.rstrip('\n').split(';') andexfield = lstData[0] if andexfield == elem: found = True do bladibla if not found: print(...) | |
Re: Here is a code that works for me from Tkinter import * class App(object): def __init__(self, width=256, height=256): self.width = width self.height = height self.root = Tk() self.root.title("tkinter_test01") self.root.geometry("%sx%s"%(self.width, self.height)) self.canvas = Canvas(self.root, width=self.width, height=self.height) self.canvas.pack() self.views = [win1(self.canvas), win2(self.canvas)] self.view_idx = 0 self.canvas.bind("<Button-1>", self.switch_view) self.current_view.repaint_canvas() def switch_view(self, event): self.view_idx … | |
Re: `pickle.loads()` works very well unless the pickle was written with a different version of python. What you can do is check the integrity of your data by sending the data together with an md5 or sha sum (see module `hashlib`). Your remote process must compute the checksum of the pickled … | |
Re: I have formulas, if `(x0, y0)` and `(x1, y1)` are two points on the track. The line joining them has the equation (y1-y0) * x - (x1-x0) * y = x0 * y1 - x1 * y0 The parallel line on the right at a distance `r` has the equation … | |
Re: searchMaze() creates a path_so_far which is a list containing a single element (start_pos), then it calls searchMazeRecurse() if start_pos is different from finish_pos. hey! this is my 3000th post ! let's clink glasses. | |
Re: Can you attach a zip with the gif images, so that we can run the code ? | |
Re: Take a page containing a list of sentences, like [this one](http://ufal.mff.cuni.cz/~toman/pedt_manual/ar01.html) (take only the first 5 sentences). Then with a calculator, compute the average number of words per sentence by hand and note carefully everything you do. This should give you a working algorithm. Write pseudo code, then python code. | |
Re: Perhaps use the `after()` method like in [this example](http://www.daniweb.com/software-development/python/code/216785/tkinter-digital-clock-python). | |
Re: The first thing to do is to avoid `import *`. Import only specific names. What you could do in this case is a function # file RenderUI.py def main(): app = QtGui.QApplication(sys.argv) app.setStyle("cleanlooks") win = Window() win.show() sys.exit(app.exec_()) and in the other file # file Render.py from RenderUI import main … | |
Re: You can use a namedtuple as a simple container from collections import namedtuple FileInfo = namedtuple("FileInfo", "path foo bar baz") mylist=[] for file in glob.glob(inputpath+"\\*.txt"): mylist.append(FileInfo(file, value1, value2, value3)) import pickle pkl = "fileinfo.pkl" with open(pkl, "wb") as ofh: pickle.dump(mylist, ofh) with open(pkl, "rb") as ifh: print(pickle.load(ifh)) |
The End.