from distutils.sysconfig import get_python_lib
Yes, I knew there was a function like this, but I couldn't remember where it was. Thanks.
from distutils.sysconfig import get_python_lib
Yes, I knew there was a function like this, but I couldn't remember where it was. Thanks.
You can also use format
message = "z's value is {z:0{digits}n}".format(z=2, digits=3)
print(message)
It takes a large amount of self control not to respond with
Can Python do this? (Who are you, Steve Urkel)
I need help (We all do but most of us can't afford a psychiatrist)
Help (Have you fallen and can't get up?)
The answer to "Can Python do this ?" is usually Yes.
"I need help" often means it's homework due in 2 hours.
Thanks a million!!! It works.
great !
ImportError: Bad magic number in C:\Python26\lib\site-packages\graphics.pyc
What is "Bad magic number?"
Did you place a 'graphics.py' (good) or a 'graphic.pyc' (bad) in the site-packages folder ? Try to remove the '.pyc' and run again, it may work. Otherwise, you can attach graphics.py to a post, so that I try it with my python 2.6.
A simple thing to do is to put the file "graphics.py" in a folder named "site-packages" which is a subfolder of your python Lib folder. You should locate it easily on your computer.
Another solution is to create another folder where you want to put importable modules, for example "C:/pymods" (if you're using windows) or "$HOME/pymods" (if you're using linux) and set an environment variable PYTHONPATH to the value "C:/pymods" (or "$HOME/pymods"), and then put the graphics.py in your folder pymods.
Here is a script which should work for 1 .pdb file and many .pd files. It creates the new versions of the .pd files (with less lines) in a separate output directory. See the usage at the end of the script. Let me know if it works !
#!/usr/bin/env python
import os
from os.path import join as pjoin, isdir, isfile
class DataFile(object):
def __init__(self, path):
self.path = path
def lines(self):
for line in open(self.path):
yield line
@staticmethod
def key(line):
return tuple(line.strip().split()[2:6])
class Pdb(DataFile):
def __init__(self, path):
DataFile.__init__(self, path)
self._keys = None
def keys(self):
if self._keys is None:
self._keys = set(self.key(line) for line in open(self.path))
return self._keys
class Pd(DataFile):
def __init__(self, path):
DataFile.__init__(self, path)
def filtered_lines(self, pdb):
keys = pdb.keys()
for line in self.lines():
if self.key(line) in keys:
yield line
def dump(self, output, pdb):
for line in self.filtered_lines(pdb):
output.write(line)
output.close()
class Output(DataFile):
def __init__(self, path):
DataFile.__init__(self, path)
self.ofile = open(path, "w")
def write(self, *args):
return self.ofile.write(*args)
def close(self):
self.ofile.close()
class Directory(object):
def __init__(self, path):
self.path = path
def names(self, extension=None):
for name in os.listdir(self.path):
if extension is None or name.endswith(extension):
yield name
def process(pdb_file, pd_dir, output_dir):
if isdir(output_dir):
raise ValueError("Output dir must not exist")
else:
os.mkdir(output_dir)
pdb = Pdb(pdb_file)
pd_dir = Directory(pd_dir)
for name in pd_dir.names(".pd"):
pd = Pd(pjoin(pd_dir.path, name))
output = Output(pjoin(output_dir, name))
pd.dump(output, pdb)
def main():
from sys import argv
pdb_file, pd_dir, output_dir = argv[-3:]
if pdb_file.endswith(".pdb") and isfile(pdb_file) and isdir(pd_dir) and not isdir(output_dir):
pass
else:
raise RuntimeError("""Usage:
<executable> pdb_file pd_dir output_dir
where
* pdb_file: an existing .pdb …
You can also do this without a loop
#!/usr/bin/env python
import re
nonletters = re.compile("[^a-zA-Z]+")
def letters_only(mystring):
return nonletters.sub(lambda m: '', mystring)
print(letters_only("Madam, in Eden I'm Adam!"))
""" my output --->
MadaminEdenImAdam
"""
If you have 10 file1 and 2000 file2, it makes 20000 file3 (output files). You should explain clearly what you want:
* Are the file1 in a separate directory ? How do you recognize that a file is a file1 ?
* Same questions for the file2s
* Do you really want 20000 output files ? What should be their names ?
Should they be in separates directories ?
Also I think I interverted file1 and file2 in the code. What should the output file contain:
* the lines from file1 which don't appear in file2 OR
* the lines from file2 which don't appear in file 1 ?
I think you could try something like this
def key(line):
return tuple(line.strip().split()[2:6])
def make_key_set(file_path):
return set(key(line) for line in open(file_path))
def filtered_lines(file_path1, file_path2):
key_set = make_key_set(file_path2)
return (line for line in open(file_path1) if key(line) in key_set)
if __name__ == "__main__":
file3 = open("file3", "w")
for line in filtered_lines("file1", "file2"):
file3.write(line)
file3.close()
(I used "file1", "file2" for the source files and "file3" for the destination file).
Wow!
That explains so much, thanks! I've written my own snippet, much like yours:
foo = open("PREFIX.txt", "r+") text = foo.read
You must CALL the read method to get the file's content
text = foo.read()
Also please mark your other thread with the same error as solved.
If it's not too much trouble, would you mind explaining step-by-step what the code does please?
The statement
special = re.compile(r"[etn]")
creates a regular expression object, which represents the set of characters 'e', 't' or 'n'. When
special.sub(escape, text)
is executed, all the occurrences of these characters are matched in the text and replaced by the output of the function 'escape'. A new string is returned.
The function 'escape' takes a 'match object' as argument which represents a match of the regex in a string and returns the text of the match preceded by a backslash.
You can use regular expressions and the re.sub function, like this
import re
special = re.compile(r"[etn]")
def escape(match):
return "\\" + match.group(0)
if __name__ == "__main__":
text = "This is a test sentence."
print text
print special.sub(escape, text)
r""" my output --->
This is a test sentence.
This is a \t\es\t s\e\n\t\e\nc\e.
"""
When you open a file, the cursor is at the beginning of the file. However
myfile.seek(0)
goes to the beginning of the file. Finally, read this.
In fact, there is a simpler method
def remove_all(sub, s):
"""
>>> remove_all('an', 'banana')
'ba'
>>> remove_all('cyc', 'bicycle')
'bile'
>>> remove_all('iss', 'Mississippi')
'Mippi'
"""
return s.replace(sub, '')
if __name__ == '__main__':
import doctest
doctest.testmod()
I don't understand your question, re.sub replaces every occurrence of a pattern by a given string, that's how it works.
A possible implementation of remove_all
import re
def remove_all(sub, s):
"""
>>> remove_all('an', 'banana')
'ba'
>>> remove_all('cyc', 'bicycle')
'bile'
>>> remove_all('iss', 'Mississippi')
'Mippi'
"""
return re.sub(re.escape(sub), '', s)
if __name__ == '__main__':
import doctest
doctest.testmod()
Note that a regex is compiled on each call.
In the "if choice" sequence, you should replace raw_input by input because you want the user input to be interpreted as a number and not as a string. Also read this about how to post python code in this forum.
You can enter a python list and then convert it using eval
userInput = input("Enter a python list: ")
mylist = eval(userInput.strip())
# check that it's a list
assert(isinstance(mylist, list))
print(mylist)
""" running the program in a shell:
$ python3 myinput.py
Enter a python list: [3, 4, 5]
[3, 4, 5]
"""
I discovered a new python book today http://www.linuxtopia.org/online_books/programming_books/python_programming/index.html.
I suggest that you write a module
# mystartup.py
import os, sys
site_packages = os.path.join(os.path.split(os.__file__)[0], "site-packages")
sys.path.append(site_packages)
and put this module somewhere on your python path. Then when you write a python program, you simply put
# at the top of your main program
import mystartup
This should work even if you have different versions of python.
You could use
reply = raw_input("Enter your choice: ")
reply = reply.strip()
if reply not in ("1", "2"):
print("Not a valid choice")
else:
reply = int(reply)
You can always replace a for loop by a while loop:
for item in sequence:
do_something()
is replaced by
sequence = list(sequence) # <--unnecessary if sequence is a string, tuple or list
i = 0
while i < len(sequence):
item = sequence[i]
do_something()
i += 1
but nobody needs to do that :)
What I wrote doesn't do anything, it only computes the path to site-packages.
What you should do is paste your sys.path here (before you do anything with it).
You can get the path to the site-packages directory like this
>>> import os
>>> os.path.join(os.path.split(os.__file__)[0], "site-packages")
'/usr/lib64/python2.6/site-packages'
With python 3:
>>> import os
>>> os.path.join(os.path.split(os.__file__)[0], "site-packages")
'/usr/local/lib/python3.1/site-packages'
(on the same machine).
However, you shouldn't normally need to put the site-packages in sys.path yourself. I'd like to see the value of your sys.path just after you start python.
Hey, everyone. I know how to strip certain characters from a string using for loop. Can you give an example of how that can be done with the use of while loop?
Please post your code with the for loop and we'll rewrite it with a while loop :)
Any idea for windows?
google setting process priority on windows may be ?
It's probably a question of setting the process' priority. On linux, you would use the renice command.
(removed first line since I am using Python25).
Why don't you install 2.6 ? It's even better.
This should work
value = min(x for x in temperature_sequence if x > 0)
Note: this raises ValueError if all temperatures are below 0.
I think you should learn python now and later go into C++. Python will teach you programming and give you an object oriented way of thinking. This will be very useful for the C++ class. Later, you'll discover that it takes hundreds of lines to do in C++ what you can do in a few lines of python, but that C++ runs faster. I would not recommend C++ as a beginner's language.
Indeed
Python 3.1.1 (r311:74480, Sep 8 2009, 15:48:28)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print(repr(input("enter your input: ")))
enter your input: 4, 5
'4, 5'
So the input returned a single string.
Ok, thanks for the correction.
It's much easier to use a gui interface like wxpython than writing a program with curses. If you want to output text, wxpython has widgets that can do it very well.
Gribouillis ur a genius!!
Have to follow the above procedure at each login to the system.
I know.
Consider upgrading to linux.
At the easy risk of asking something already asked a hundred times...
Curses doesn't work for me.
I use 2.6 on a Vista
It gives an error saying it can't call up a part of the module that came with the program.
... Uhm... help.. T_T
~Pixel
You had 2 bad ideas:
1) use vista
2) use curses
Anyway, let's have a look. What's the exception traceback ? (between code tags please)
Never seen that on a fresh installation. Is it the same tracback if you uninstall everything and reinstall python 2.6 ?
Also, you should check if you don't have a bad python-related environment variable.
Did you try python -v
? Please post the traceback between code tags http://www.daniweb.com/forums/announcement114-3.html.
How can we save a text file we make using python in another directory?The default directory is always the directory in which , the program is ? is there any way to change this?Can this be done when we are creating the file (FILE=open(filename,"w"))
thanks in advance
Instead of filename, you can give a path to a file in another directory to open. For example
from os.path import join as pjoin
filename = "myfile.txt"
path_to_file = pjoin("C:", "foo", "bar", "baz", filename)
FILE = open(path_to_file, "w")
s='1234444432187667890000568984'
print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
A possible use of static methods is to add constructors to a class, like in this example
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "Person({name}, {age})".format(name=self.name, age=self.age)
@staticmethod
def from_sequence(seq):
name, age = list(seq)
return Person(name, age)
@staticmethod
def from_dict(dic):
return Person(dic["name"], dic["age"])
if __name__ == "__main__":
my_tuple = ("John", 32)
my_dict = {"name":"Fred", "age":55}
anna = Person("anna", 15)
john = Person.from_sequence(my_tuple)
fred = Person.from_dict(my_dict)
for person in (anna, john, fred):
print(person)
Ok, you can change the text with
l.setText(str(300)) # the text now shows 300
note that the letter 'l' is a bad variable name. Good variable names have at least 3 characters (except for loop variables like i, j, ...)
For the doc, you could use
from zellegraphics import *
from pydoc import HTMLDoc
textdoc = HTMLDoc()
out = open("mydoc.html", "w")
out.write(textdoc.document(Text))
to get a file mydoc.html to view in your browser.
About the floating point test, you should use if center >= 400.0
rather that ==
because floating point numbers seldom happen to be equal. If the value is 400.00000001, dx should be set to -10 for example.
Your move function should return the next dx and dy. You could write this
from zellegraphics import *
##Write a program to animate a circle bouncing around a window. The basic idea
##is to start the circle somewhere in the interior of the window. Use variables
##dx and dy (both initalized to 10) to control the movement of the circle. Use a
##large counted loop (say 10000 iterations), and each time through the loop move
##the circle using dx and dy. When the x-value of the center of the circle gets
##too high (it hits the edge), change dx to -1. When it gets too low, change dx
##back to 1. Use a similar approach for dy.
#Set up a window 400 by 400
win = GraphWin("Circle Moving", 400, 400)
#Set up circle that will travel around the window
c = Circle(Point (200,200), 30)
c.draw(win)
x = 1
l = Text(Point (200,200), x)
l.draw(win)
def move(x,y):
win.getMouse()
dx = x
dy = y
c.move(dx,dy)
l.move(dx,dy)
center = c.getCenter()
center = center.getX()
print center
if center == 400.0:
dx = -10
return dx, dy
def main():
dx, dy = 10, -10
for i in range(100):
dx, dy = move(dx, dy)
main()
To change the text, we need to have some documentation about Text. Can you run the following code ?
from zellegraphics import *
from pydoc import TextDoc
textdoc = TextDoc()
out = open("mydoc.txt", "w")
out.write(textdoc.document(Text))
If it works, please put the content of the file mydoc.txt in a …
You can use the "format" method
# This program computes right triangles
import math
print "This program computes the hypotenuse of a right triangle with the sides a and b."
a = input("Enter the length of the first leg to the nearest inch: ")
b = input("Enter the length of the second leg to the nearest inch: ")
# Calculate the length of the hypotenuse:
c = math.sqrt((a**2) + (b**2))
# Calculate the area of the triangle
Area = (a*b)/2.0
# To create a line across:
print "-----------------------------------"
print "The hypotenuse is: {c:.2f} inches.".format(c=c)
print "The area is: {area:.2f} sq in.".format(area=Area)
So what you're saying is that as the number of permutations exceeds the period of Python's random number generator, each index has an equally probable chance of being relocated to the beginning? Can you prove this?
I think I understand your point now. There must be a limitation somewhere when n is large. However, note that the builtin shuffle function takes an optional argument 'random' which allows you to pass your own random generator. So I still believe that the best method is to use shuffle, but for large n, write your own random generator with a larger period. An interesting point would be to have an order of magnitude of the n for which this problem arises.
Because the number of permutations exceeds the period of the random number generator, some sequences will never be returned by the function.
I still don't agree. It's very easy to write a shuffle function
from random import randrange
def my_shuffle(the_list):
n = len(the_list)
while n > 1:
i = randrange(n)
the_list[i], the_list[n-1] = the_list[n-1], the_list[i]
n -= 1
L = range(10)
my_shuffle(L)
print(L)
Shuffle generates only one permutation. Now since each permutation of n objects is the product of at most n transpositions, you only need to generate at most n random transpositions in a set of order O(n^2) possible transpositions.