How do I split on all nonalphanumeric characters, EXCEPT the apostrophe?
re.split('\W+',text)
works, but will also split on apostrophes. How do I add an exception to this rule?
Thanks!
If I have a string that looks like either
./A/B/c.d
OR
.\A\B\c.d
How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed.
This problem kinda boils down to: How do I get the last of a specific character in a string?
Basically, I want the path of a file without the file part of it.
i have a file its name is 5_1.txt in a directory i named it direct ,
how can i read that file using the instruction read.
i verified the path using :
os.getcwd()
os.path.exists(direct)
the result was
True
x_file=open(direct,'r')
and i got this error :
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
x_file=open(direct,'r')
IOError: [Errno 13] Permission denied
i don't know why i can't read the file ? any suggestion ?
thanks .
I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(funtions, methods...) as would be normal for a unittest.
It does not need to be a unittest and I don't what to automatically convert the files I just want to monitor the py3 compliance of files in a unittest like manor. I can't seem to find any documentation or examples for this.
An example and/or documentation would be great.
Thanks
Here's the deal. I'm trying to write an arkanoid clone game and the thing is that I need a window menu like you get in pyGTK. For example File-(Open/Save/Exit) .. something like that and opening an "about" context where the author should be written.
I'm already using pyGame for writting the game logic. I've tried pgu to write the GUI but that doesn't help me, altough it has those menu elements I'm taking about, you can't include the screen of the game in it's container.
Does anybody know how to include such window menus with the usage of pyGame ?
I'm using the following code to initialize logging in my application.
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# log to a file
directory = '/reserved/DYPE/logfiles'
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(directory, 'dype_%s.log' % now)
file_handler = logging.FileHandler(filename)
file_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(filename)s, %(lineno)d, %(funcName)s: %(message)s")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# log to the console
console_handler = logging.StreamHandler()
level = logging.INFO
console_handler.setLevel(level)
logger.addHandler(console_handler)
logging.debug('logging initialized')
How can I close the current logging file and restart logging to a new file?
Note: I don't want to use RotatingFileHandler, because I want full control over all the filenames and the moment of rotation.
i wrote the code like this
import smtplib
server=smtplib.SMTP('localhost')
then it raising an error like
error: [Errno 10061] No connection could be made because the target machine actively refused it
i am new to SMTP can you tell what exactly the problem is
ok I know that this should be simple... anyways say:
line = "$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6,123,75,-0.4,1.4*49"
I want to strip out the spaces. I thought you would just do this
line = line.strip()
but now line is still '$W5M5A,100527,142500,730301c44892fd1c,2,686.5 4,333.96,0,0,28.6,123,75,-0.4,1.4*49' instead of '$W5M5A,100527,142500,730301c44892fd1c,2,686.54,333.96,0,0,28.6,123,75,-0.4,1.4*49'
any thoughts?
hi,
i am using cairoplot, to make graphs, however the file from where i am reading the data is growing huge and its taking a long time to process the graph
is there any real-time way to produce cairo graph, or at least store the previous readings..like rrd.
-krisdigitx
I am trying to search hindi words contained one line per file in file-1 and find them in lines in file-2. I have to print the line numbers with the number of words found.
This is the code:
import codecs
hypernyms = codecs.open("hindi_hypernym.txt", "r", "utf-8").readlines()
words = codecs.open("hypernyms_en2hi.txt", "r", "utf-8").readlines()
count_arr = []
for counter, line in enumerate(hypernyms):
count_arr.append(0)
for word in words:
if line.find(word) >=0:
count_arr[counter] +=1
for iterator, count in enumerate(count_arr):
if count>0:
print iterator, ' ', count
This is finding some words, but ignoring some others
The input files are:
File-1:
????
???????
File-2:
???????, ????-????
?????-???, ?????-???, ?????_???, ?????_???
????_????, ????-????, ???????_????
????-????
This gives output:
0 1
3 1
Clearly, it is ignoring ??????? and searching for ???? only. I have tried with other inputs as well. It only searches for one word. Any idea how to correct this?
I'm trying to use reserved words in my grammar:
reserved = {
'if' : 'IF',
'then' : 'THEN',
'else' : 'ELSE',
'while' : 'WHILE',
}
tokens = [
'DEPT_CODE',
'COURSE_NUMBER',
'OR_CONJ',
'ID',
] + list(reserved.values())
t_DEPT_CODE = r'[A-Z]{2,}'
t_COURSE_NUMBER = r'[0-9]{4}'
t_OR_CONJ = r'or'
t_ignore = ' \t'
def t_ID(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
if t.value in reserved.values():
t.type = reserved[t.value]
return t
return None
However, the t_ID rule somehow swallows up DEPT_CODE and OR_CONJ. How can I get around this? I'd like those two to take higher precedence than the reserved words.
I have a binary data format consisting of 18,000+ packed int64s, ints, shorts, bytes and chars. The data is packed to minimize it's size, so they don't always use byte sized chunks. For example, a number whose min and max value are 31, 32 respectively might be stored with a single bit where the actual value is bitvalue + min, so 0 is 31 and 1 is 32. I am looking for the most efficient way to unpack all of these for subsequent processing and database storage.
Right now I am able to read any value by using either struct.unpack, or BitBuffer. I use struct.unpack for any data that starts on a bit where (bit-offset % 8 == 0 and data-length % 8 == 0) and I use BitBuffer for anything else.
I know the offset and size of every packed piece of data, so what is going to be the fasted way to completely unpack them?
Many thanks.
I'm looking for a way to compress an ascii-based string, any help?
I need also need to decompress it. I tried zlib but with no help.
What can I do to compress the string into lesser length?
code:
def compress(request):
if request.POST:
data = request.POST.get('input')
if is_ascii(data):
result = zlib.compress(data)
return render_to_response('index.html', {'result': result, 'input':data}, context_instance = RequestContext(request))
else:
result = "Error, the string is not ascii-based"
return render_to_response('index.html', {'result':result}, context_instance = RequestContext(request))
else:
return render_to_response('index.html', {}, context_instance = RequestContext(request))
Hello, I have got some code to pass in a variable into a script from the command line. The script is:
import sys, os
def function(var):
print var
class function_call(object):
def __init__(self, sysArgs):
try:
self.function = None
self.args = []
self.modulePath = sysArgs[0]
self.moduleDir, tail = os.path.split(self.modulePath)
self.moduleName, ext = os.path.splitext(tail)
__import__(self.moduleName)
self.module = sys.modules[self.moduleName]
if len(sysArgs) > 1:
self.functionName = sysArgs[1]
self.function = self.module.__dict__[self.functionName]
self.args = sysArgs[2:]
except Exception, e:
sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e))
def execute(self):
try:
if self.function:
self.function(*self.args)
except Exception, e:
sys.stderr.write("%s %s\n" % ("PythonCall#execute", e))
if __name__=="__main__":
test = test()
function_call(sys.argv).execute()
This works by entering ./function <function> <arg1 arg2 ....>. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that function(var): is in a class. I was hoping for some ideas on how to modify my function_call class to accept this.
Thanks for any help.
I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least 1 file for each day).
In the long run, I'm trying to find the file from each day with the latest creation/modification time. If there is a way to bundle that into the iterations that are required above to save some CPU cycles, that would be even more ideal. Then I'd have one flat array with 31 files, one for each day, for the latest file created on each individual day.
First off, I'm relatively new to Google App Engine, so I'm probably doing something silly.
Say I've got a model Foo:
class Foo(db.Model):
name = db.StringProperty()
I want to use name as a unique key for every Foo object. How is this done?
When I want to get a specific Foo object, I currently query the datastore for all Foo objects with the target unique name, but queries are slow (plus it's a pain to ensure that name is unique when each new Foo is created).
There's got to be a better way to do this!
Thanks.
I am looking into the unittest package, and I'm not sure of the proper way to structure my test cases when writing a lot of them for the same method. Say I have a fact function which calculates the factorial of a number; would this testing file be OK?
import unittest
class functions_tester(unittest.TestCase):
def test_fact_1(self):
self.assertEqual(1, fact(1))
def test_fact_2(self):
self.assertEqual(2, fact(2))
def test_fact_3(self):
self.assertEqual(6, fact(3))
def test_fact_4(self):
self.assertEqual(24, fact(4))
def test_fact_5(self):
self.assertFalse(1==fact(5))
def test_fact_6(self):
self.assertRaises(RuntimeError, fact, -1)
#fact(-1)
if __name__ == "__main__":
unittest.main()
It seems sloppy to have so many test methods for one method. I'd like to just have one testing method and put a ton of basic test cases (ie 4! ==24, 3!==6, 5!==120, and so on), but unittest doesn't let you do that.
What is the best way to structure a testing file in this scenario?
Thanks in advance for the help.
Hello, i have 2 classes.
How i call first.TQ in Second ? Without creating object First in Second.
class First:
def __init__(self):
self.str = ""
def TQ(self):
pass
def main(self):
T = Second(self.str) # Called here
class Second():
def __init__(self):
list = {u"RANDINT":first.TQ} # List of funcs maybe called in first
.....
.....
return data
Is there a more Pythonic way to put this loop together?:
while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
UPDATE:
I think this syntax is probably what I'm going to go with:
while tree.getChildren():
tree = tree.getChildren()[0]
Trying to integrate openmeetings with django website, but can't understand how properly configure ImportDoctor:
(here :// replaced with __ 'cause spam protection)
print url
http://sovershenstvo.com.ua:5080/openmeetings/services/UserService?wsdl
imp = Import('http__schemas.xmlsoap.org/soap/encoding/')
imp.filter.add('http__services.axis.openmeetings.org')
imp.filter.add('http__basic.beans.hibernate.app.openmeetings.org/xsd')
imp.filter.add('http__basic.beans.data.app.openmeetings.org/xsd')
imp.filter.add('http__services.axis.openmeetings.org')
d = ImportDoctor(imp)
client = Client(url, doctor = d)
client.service.getSession()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/site-packages/suds/client.py", line 539, in call
return client.invoke(args, kwargs)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 598, in invoke
result = self.send(msg)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 627, in send
result = self.succeeded(binding, reply.message)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 659, in succeeded
r, p = binding.get_reply(self.method, reply)
File "/usr/lib/python2.6/site-packages/suds/bindings/binding.py", line 159, in get_reply
resolved = rtypes[0].resolve(nobuiltin=True)
File "/usr/lib/python2.6/site-packages/suds/xsd/sxbasic.py", line 63, in resolve
raise TypeNotFound(qref)
suds.TypeNotFound: Type not found: '(Sessiondata, http__basic.beans.hibernate.app.openmeetings.org/xsd, )'
what i'm doing wrong? please help and sorry for my english, but you are my last chance to save position :(
need webinars at morning (2.26 am now)
Hi,
I have some strings that I want to delete some unwanted characters from them.
For example: Adam'sApple ---- AdamsApple.(case insensitive)
Can someone help me, I need the fastest way to do it, cause I have a couple of millions of records that have to be polished.
Thanks
Hello everybody,
I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [141, 25, 14, 10]]
Would you help me with this?
from google.appengine.ext import db
class Log(db.Model):
content = db.StringProperty(multiline=True)
class MyThread(threading.Thread):
def run(self,request):
#logs_query = Log.all().order('-date')
#logs = logs_query.fetch(3)
log=Log()
log.content=request.POST.get('content',None)
log.put()
def Log(request):
thr = MyThread()
thr.start(request)
return HttpResponse('')
error is :
Exception in thread Thread-1:
Traceback (most recent call last):
File "D:\Python25\lib\threading.py", line 486, in __bootstrap_inner
self.run()
File "D:\zjm_code\helloworld\views.py", line 33, in run
log.content=request.POST.get('content',None)
NameError: global name 'request' is not defined