pySerial - accessing GSM module failed
Hello all,
I'm newbie in the serial buissness and I beed some Help. I'm a student at my
last year and I got final assaignment.
My goal is to comunicate with SIM free, GSM Module through computer. I want
to simulate SIM card by receiving and transferring data from my code.
In order to understand how to comunicate with the GSM module I took an
existing module which gut RS232 connector and connected it to the computer.
I ran my python code:
class MySerial():
def __init__ (self,port,baundrate,)
self.s = serial.Serial(port,baundreate,)
def read(self,size=1):
txt = self.s.read(size)
def write(self,text=''):txt = self.s.write(text)
def main():
obj = MySerial('COM1')
obj.write('ATI')
sleep(1)
obj.read(10)
the code run and I send the comman 'ATI' which ask the GSM Module if
everything is OK.
the read line returs 'ATI'. echo to my write function.
Whenever I run this comman ('ATI') through hyperterminal I gut the result :
232 OK
Does any one got an Idea why my code isn't getting the same answer from the
GSM Module?
thanks
dave
--
http://mail.python.org/mailman/listinfo/python-list
creating an artificial "last element" in sort list
a = ['a', 'b', x] b = sorted(a) What does x need to be to always be last on an ascending sort no matter what 'a' and 'b' are within reason... I am expecting 'a' and 'b' will be not longer than 10 char's long I tried making x = '' and believe it or not, this appears FIRST on the sort!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: creating an artificial "last element" in sort list
more clearer, this is a more realistic use case: ['awefawef', 'awefawfsf', 'awefsdf', 'zz', 'zz', 'zz'] and the quantity of ''zz'' would be dynamic. On Friday, September 28, 2012 4:46:15 PM UTC-7, Ian wrote: > > > a = ['a', 'b', x] > > > > > > b = sorted(a) > > > > > > What does x need to be to always be last on an ascending sort no matter > > what 'a' and 'b' are within reason... I am expecting 'a' and 'b' will > > be not longer than 10 char's long I tried making x = '' > > and believe it or not, this appears FIRST on the sort!!! > > > > It appears last when I run the code. > > > > To answer your question, though, if you want to force x to be last, > > then I suggest removing it from the list and then appending it to the > > end. -- http://mail.python.org/mailman/listinfo/python-list
Job
Looking for entry to mid level Python Developer for Contract job in New England. Let me know if you want to hear more. -- http://mail.python.org/mailman/listinfo/python-list
Help with Python/Eyed3 MusicCDIdFrame method
Hi,
I’m trying to get the ID3 tags of an mp3 file. I trying to use the
MusicCDIdFrame
method but I can’t seem to get it right. Here is a code snippet:
import eyed3
import eyed3.id3
import eyed3.id3.frames
import eyed3.id3.apple
import eyed3.mp3
myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3")
myTitle = myID3.tag.title
myArtist = myID3.tag.artist
myAlbum = myID3.tag.album
myAlbumArtist = myID3.tag.album_artist
myComposer = myID3.tag.composer
myPublisher = myID3.tag.publisher
myGenre = myID3.tag.genre.name
myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'')
When I run this, I get the following error:
File "/Documents/Python/Test1/main.py", line 94, in
myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'')
AttributeError: 'Mp3AudioFile' object has no attribute 'id3'
Any help or suggestion greatly appreciated.
All the Best
Dave
--
https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python/Eyed3 MusicCDIdFrame method
Thanks! That fixed it!
> On 6 Jun 2022, at 18:46, MRAB wrote:
>
> On 2022-06-06 11:37, Dave wrote:
>> Hi,
>> I’m trying to get the ID3 tags of an mp3 file. I trying to use the
>> MusicCDIdFrame
>> method but I can’t seem to get it right. Here is a code snippet:
>> import eyed3
>> import eyed3.id3
>> import eyed3.id3.frames
>> import eyed3.id3.apple
>> import eyed3.mp3
>> myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3")
>> myTitle = myID3.tag.title
>> myArtist = myID3.tag.artist
>> myAlbum = myID3.tag.album
>> myAlbumArtist = myID3.tag.album_artist
>> myComposer = myID3.tag.composer
>> myPublisher = myID3.tag.publisher
>> myGenre = myID3.tag.genre.name
>> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'')
>> When I run this, I get the following error:
>> File "/Documents/Python/Test1/main.py", line 94, in
>> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'')
>> AttributeError: 'Mp3AudioFile' object has no attribute 'id3'
>> Any help or suggestion greatly appreciated.
> That line should be:
>
> myCDID = eyed3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'')
>
> Also remember that some attributes might be None, e.g. 'myID3.tag.genre'
> might be None.
>
> Another point: it's probably not worth importing the submodules of 'eyed3';
> you're not gaining anything from it.
> --
> https://mail.python.org/mailman/listinfo/python-list
> <https://mail.python.org/mailman/listinfo/python-list>
--
https://mail.python.org/mailman/listinfo/python-list
How to test characters of a string
Hi, I’m new to Python and have a simple problem that I can’t seem to find the answer. I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want “Trinket”. I can’t for the life of work out how to do it in Python? All the Best Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Thanks a lot for this! isDigit was the method I was looking for and couldn’t
find.
I have another problem related to this, the following code uses the code you
just sent. I am getting a files ID3 tags using eyed3, this part seems to work
and I get expected values in this case myTitleName (Track name) is set to
“Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” (File
Name with the Track number prepended). The is digit test works and
myCompareFileName is set to “Deadlock Holiday”, so they should match, right?
However the if myCompareFileName != myTitleName always gives a mismatch! What
could cause two string that look the fail to not match properly?
myCompareFileName = myFile
if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit():
myCompareFileName = myCompareFileName[3:]
if myCompareFileName != myTitleName:
print('File Name Mismatch - Artist: ',myArtistName,' Album:
',myAlbumName,' Track:',myTitleName,' File: ',myFile)
Thanks a lot
Dave
> On 7 Jun 2022, at 21:58, De ongekruisigde
> wrote:
>
> On 2022-06-07, Dave wrote:
>> Hi,
>>
>> I’m new to Python and have a simple problem that I can’t seem to find the
>> answer.
>>
>> I want to test the first two characters of a string to check if the are
>> numeric (00 to 99) and if so remove the fist three chars from the string.
>>
>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want
>> “Trinket”. I can’t for the life of work out how to do it in Python?
>
>
> s[3:] if s[0:2].isdigit() else s
>
>
>> All the Best
>> Dave
>>
>
> --
> You're rewriting parts of Quake in *Python*?
> MUAHAHAHA
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
It depends on the language I’m using, in Objective C, I’d use isNumeric, just wanted to know what the equivalent is in Python. If you know the answer why don’t you just tell me and if you don’t, don’t post! > On 7 Jun 2022, at 22:08, [email protected] wrote: > > On 2022-06-07 at 21:35:43 +0200, > Dave wrote: > >> I’m new to Python and have a simple problem that I can’t seem to find >> the answer. > >> I want to test the first two characters of a string to check if the >> are numeric (00 to 99) and if so remove the fist three chars from the >> string. > >> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >> “Trinket”. I can’t for the life of work out how to do it in Python? > > How would you do it without Python? > > Given that if the string is called x, then x[y] is the y'th character > (where what you would call "the first character," Python calls "the > zeroth character"), describe the steps you would take *as a person* (or > in some other programming language, if you know one) to carry out this > task. > > Translating that algorithm to Python is the next step. Perhaps > https://docs.python.org/3/library/string.html can help. > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Hi, No, I’ve checked leading/trailing whitespace, it seems to be related to the variables that are returned from eyed3 in this case, for instance, I added a check for None: myTitleName = myID3.tag.title if myTitleName is None: continue Seems like it can return a null object (or none?). > On 7 Jun 2022, at 22:35, De ongekruisigde > wrote: > > On 2022-06-07, Dave <mailto:[email protected]>> wrote: >> Thanks a lot for this! isDigit was the method I was looking for and couldn’t >> find. >> >> I have another problem related to this, the following code uses the code you >> just sent. I am getting a files ID3 tags using eyed3, this part seems to >> work and I get expected values in this case myTitleName (Track name) is set >> to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” >> (File Name with the Track number prepended). The is digit test works and >> myCompareFileName is set to “Deadlock Holiday”, so they should match, >> right? >> >> However the if myCompareFileName != myTitleName always gives a mismatch! >> What could cause two string that look the fail to not match properly? > > Possibly leading or trailing spaces, or upper/lower case differences? > > >> myCompareFileName = myFile >> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >>myCompareFileName = myCompareFileName[3:] >> >> if myCompareFileName != myTitleName: >> print('File Name Mismatch - Artist: ',myArtistName,' Album: >> ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >> Thanks a lot >> Dave >> >>> On 7 Jun 2022, at 21:58, De ongekruisigde >>> wrote: >>> >>> On 2022-06-07, Dave wrote: >>>> Hi, >>>> >>>> I’m new to Python and have a simple problem that I can’t seem to find the >>>> answer. >>>> >>>> I want to test the first two characters of a string to check if the are >>>> numeric (00 to 99) and if so remove the fist three chars from the string. >>>> >>>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >>>> “Trinket”. I can’t for the life of work out how to do it in Python? >>> >>> >>> s[3:] if s[0:2].isdigit() else s >>> >>> >>>> All the Best >>>> Dave >>>> >>> >>> -- >>> You're rewriting parts of Quake in *Python*? >>> MUAHAHAHA >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> > > > -- > You're rewriting parts of Quake in *Python*? > MUAHAHAHA > -- > https://mail.python.org/mailman/listinfo/python-list > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Hi, Found it! The files name had .mp3 at the end, the problem was being masked by null objects (or whatever) being returned by eyed3. Checked for null objects and then stripped off the .mp3 and its mostly working now. I’ve got a few other eyed3 errors to do with null objects but I can sort those out tomorrow. Thanks for your help - All the Best Dave > On 7 Jun 2022, at 23:01, Dave wrote: > > Hi, > > No, I’ve checked leading/trailing whitespace, it seems to be related to the > variables that are returned from eyed3 in this case, for instance, I added a > check for None: > myTitleName = myID3.tag.title > if myTitleName is None: >continue > Seems like it can return a null object (or none?). > > >> On 7 Jun 2022, at 22:35, De ongekruisigde >> > <mailto:[email protected]>> wrote: >> >> On 2022-06-07, Dave > <mailto:[email protected]> <mailto:[email protected] >> <mailto:[email protected]>>> wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and >>> couldn’t find. >>> >>> I have another problem related to this, the following code uses the code >>> you just sent. I am getting a files ID3 tags using eyed3, this part seems >>> to work and I get expected values in this case myTitleName (Track name) is >>> set to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock >>> Holiday” (File Name with the Track number prepended). The is digit test >>> works and myCompareFileName is set to “Deadlock Holiday”, so they should >>> match, right? >>> >>> However the if myCompareFileName != myTitleName always gives a mismatch! >>> What could cause two string that look the fail to not match properly? >> >> Possibly leading or trailing spaces, or upper/lower case differences? >> >> >>> myCompareFileName = myFile >>> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >>> myCompareFileName = myCompareFileName[3:] >>> >>> if myCompareFileName != myTitleName: >>> print('File Name Mismatch - Artist: ',myArtistName,' Album: >>> ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >>> Thanks a lot >>> Dave >>> >>>> On 7 Jun 2022, at 21:58, De ongekruisigde >>>> wrote: >>>> >>>> On 2022-06-07, Dave wrote: >>>>> Hi, >>>>> >>>>> I’m new to Python and have a simple problem that I can’t seem to find the >>>>> answer. >>>>> >>>>> I want to test the first two characters of a string to check if the are >>>>> numeric (00 to 99) and if so remove the fist three chars from the string. >>>>> >>>>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >>>>> “Trinket”. I can’t for the life of work out how to do it in Python? >>>> >>>> >>>> s[3:] if s[0:2].isdigit() else s >>>> >>>> >>>>> All the Best >>>>> Dave >>>>> >>>> >>>> -- >>>> You're rewriting parts of Quake in *Python*? >>>> MUAHAHAHA >>>> -- >>>> https://mail.python.org/mailman/listinfo/python-list >>> >> >> >> -- >> You're rewriting parts of Quake in *Python*? >> MUAHAHAHA >> -- >> https://mail.python.org/mailman/listinfo/python-list >> <https://mail.python.org/mailman/listinfo/python-list> >> <https://mail.python.org/mailman/listinfo/python-list >> <https://mail.python.org/mailman/listinfo/python-list>> > -- > https://mail.python.org/mailman/listinfo/python-list > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
A, ok will do, was just trying to be a brief as possible, will post more fully in future. > On 7 Jun 2022, at 23:29, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 07:24, Barry wrote: >> >> >> >>> On 7 Jun 2022, at 22:04, Dave wrote: >>> >>> It depends on the language I’m using, in Objective C, I’d use isNumeric, >>> just wanted to know what the equivalent is in Python. >>> >>> If you know the answer why don’t you just tell me and if you don’t, don’t >>> post! >> >> People ask home work questions here and we try to teach a student with hints >> not finished answers. >> Your post was confused with a home work question. >> > > In the future, to make it look less like a homework question, show > your current code, which would provide context. Last I checked, > homework questions don't usually involve ID3 tags in MP3 files :) > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Yes, it was probably just a typeo on my part.
I’ve now fixed the majority of cases but still got two strings that look
identical but fail to match, this time (again by 10cc), “I’m Mandy Fly Me”.
I’m putting money on it being a utf8 problem but I’m stuck on how to handle it.
It’s probably the single quote in I’m, although it has worked with other songs.
Any ideas?
All the Best
Cheers
Dave
Here is the whole function/method or whatever it’s called in Python:
#
# checkMusicFiles
#
def checkMusicFiles(theBaseMusicLibraryFolder):
myArtistDict = []
#
# Loop thru Artists Folder
#
myArtistsFoldlerList = getFolderList(theBaseMusicLibraryFolder)
myArtistCount = 0
for myArtistFolder in myArtistsFoldlerList:
print('Artist: ' + myArtistFolder)
#
# Loop thru Albums Folder
#
myAlbumList = getFolderList(theBaseMusicLibraryFolder + myArtistFolder)
for myAlbum in myAlbumList:
print('Album: ' + myAlbum)
#
# Loop thru Tracks (Files) Folder
#
myAlbumPath = theBaseMusicLibraryFolder + myArtistFolder + '/' +
myAlbum + '/'
myFilesList = getFileList(myAlbumPath)
for myFile in myFilesList:
myFilePath = myAlbumPath + myFile
myID3 = eyed3.load(myFilePath)
if myID3 is None:
continue
myArtistName = myID3.tag.artist
if myArtistName is None:
continue
myAlbumName = myID3.tag.album
if myAlbumName is None:
continue
myTitleName = myID3.tag.title
if myTitleName is None:
continue
myCompareFileName = myFile[0:-4]
if myCompareFileName[0].isdigit() and
myCompareFileName[1].isdigit():
myCompareFileName = myFile[3:-4]
if myCompareFileName != myTitleName:
myLength1 = len(myCompareFileName)
myLength2 = len(myTitleName)
print('File Name Mismatch - Artist: [' + myArtistName + ']
Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' +
myCompareFileName + ']')
if (myLength1 == myLength2):
print('lengths match: ',myLength1)
else:
print('lengths mismatch: ',myLength1,' ',myLength2)
print(' ')
return myArtistsFoldlerList
> On 8 Jun 2022, at 00:07, MRAB wrote:
>
> On 2022-06-07 21:23, Dave wrote:
>> Thanks a lot for this! isDigit was the method I was looking for and couldn’t
>> find.
>> I have another problem related to this, the following code uses the code you
>> just sent. I am getting a files ID3 tags using eyed3, this part seems to
>> work and I get expected values in this case myTitleName (Track name) is set
>> to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday”
>> (File Name with the Track number prepended). The is digit test works and
>> myCompareFileName is set to “Deadlock Holiday”, so they should match, right?
> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)?
>
> [snip]
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
rotfl! Nice one! > On 8 Jun 2022, at 00:24, [email protected] wrote: > > On 2022-06-07 at 23:07:42 +0100, > Regarding "Re: How to test characters of a string," > MRAB wrote: > >> On 2022-06-07 21:23, Dave wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and >>> couldn’t find. >>> >>> I have another problem related to this, the following code uses the code >>> you just sent. I am getting a files ID3 tags using eyed3, this part seems >>> to work and I get expected values in this case myTitleName (Track name) is >>> set to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock >>> Holiday” (File Name with the Track number prepended). The is digit test >>> works and myCompareFileName is set to “Deadlock Holiday”, so they should >>> match, right? >>> >> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by >> 10cc)? > > Edsger Dijkstra originally wrote Deadlock Holiday for his band, The > Semaphores. 10cc lost the race condition and had to change the lyrics. > > Sorry. > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
I hate regEx and avoid it whenever possible, I’ve never found something that was impossible to do without it. > On 8 Jun 2022, at 00:49, dn wrote: > > On 08/06/2022 10.18, De ongekruisigde wrote: >> On 2022-06-08, Christian Gollwitzer wrote: >>> Am 07.06.22 um 21:56 schrieb Dave: >>>> It depends on the language I’m using, in Objective C, I’d use isNumeric, >>>> just wanted to know what the equivalent is in Python. >>>> >>> >>> Your problem is also a typical case for regular expressions. You can >>> create an expression for "starts with any number of digits plus optional >>> whitespace" and then replace this with nothing: >> >> Regular expressions are overkill for this and much slower than the >> simple isdigit based solution. > > ... > >> Regular expressions are indeeed extremely powerful and useful but I tend >> to avoid them when there's a (faster) normal solution. > > Yes, simple solutions are (likely) easier to read. > > RegEx-s are more powerful (and well worth learning for this reason), but > are only 'readable' to those who use them frequently. > > Has either of you performed a timeit comparison? > -- > Regards, > =dn > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
How to replace characters in a string?
Hi All,
I decided to start a new thread as this really is a new subject.
I've got two that appear to be identical, but fail to compare. After getting
the ascii encoding I see that they are indeed different, my question is how can
I replace the \u2019m with a regular single quote mark (or apostrophe)?
myCompareFile1 = ascii(myTitleName)
myCompareFile2 = ascii(myCompareFileName)
myCompareFile1: 'I\u2019m Mandy Fly Me'
myCompareFile2: "I'm Mandy Fly Me"
I tried the but it doesn’t seem to work?
myCompareFile1 = ascii(myTitleName)
myCompareFile1.replace("\u2019", "'")
myCompareFile2 = ascii(myCompareFileName)
myCompareFile2.replace("\u2019", "'")
if myCompareFile1 != myCompareFile2:
print('myCompareFile1:',myCompareFile1)
print('myCompareFile2:',myCompareFile2)
myLength1 = len(myCompareFileName)
myLength2 = len(myTitleName)
print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+
myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName +
']')
if (myLength1 == myLength2):
print('lengths match: ',myLength1)
else:
print('lengths mismatch: ',myLength1,' ',myLength2)
print(' ')
Console:
myCompareFile1: 'I\u2019m Mandy Fly Me'
myCompareFile2: "I'm Mandy Fly Me"
So it looks like the replace isn’t doing anything?
I’m an experienced developer but learning Python.
All the Best
Dave
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
PS
I’ve also tried:
myCompareFile1 = myTitleName
myCompareFile1.replace("\u2019", "'")
myCompareFile2 = myCompareFileName
myCompareFile2.replace("\u2019", "'")
Which also doesn’t work, the replace itself work but it still fails the compare?
> On 8 Jun 2022, at 10:08, Dave wrote:
>
> Hi All,
>
> I decided to start a new thread as this really is a new subject.
>
> I've got two that appear to be identical, but fail to compare. After getting
> the ascii encoding I see that they are indeed different, my question is how
> can I replace the \u2019m with a regular single quote mark (or apostrophe)?
>
> myCompareFile1 = ascii(myTitleName)
> myCompareFile2 = ascii(myCompareFileName)
> myCompareFile1: 'I\u2019m Mandy Fly Me'
> myCompareFile2: "I'm Mandy Fly Me"
>
> I tried the but it doesn’t seem to work?
> myCompareFile1 = ascii(myTitleName)
> myCompareFile1.replace("\u2019", "'")
> myCompareFile2 = ascii(myCompareFileName)
> myCompareFile2.replace("\u2019", "'")
> if myCompareFile1 != myCompareFile2:
>print('myCompareFile1:',myCompareFile1)
>print('myCompareFile2:',myCompareFile2)
>myLength1 = len(myCompareFileName)
>myLength2 = len(myTitleName)
>print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+
> myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName
> + ']')
>if (myLength1 == myLength2):
>print('lengths match: ',myLength1)
>else:
> print('lengths mismatch: ',myLength1,' ',myLength2)
>print(' ')
> Console:
>
> myCompareFile1: 'I\u2019m Mandy Fly Me'
> myCompareFile2: "I'm Mandy Fly Me"
>
> So it looks like the replace isn’t doing anything?
>
> I’m an experienced developer but learning Python.
>
> All the Best
> Dave
>
>
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi,
Thanks for this!
So, is there a copy function/method that returns a MutableString like in
objective-C? I’ve solved this problems before in a number of languages like
Objective-C and AppleScript.
Basically there is a set of common characters that need “normalizing” and I
have a method that replaces them in a string, so:
myString = [myString normalizeCharacters];
Would return a new string with all the “common” replacements applied.
Since the following gives an error :
myString = 'Hello'
myNewstring = myString.replace(myString,'e','a’)
TypeError: 'str' object cannot be interpreted as an integer
I can’t see of a way to do this in Python?
All the Best
Dave
> On 8 Jun 2022, at 10:14, Chris Angelico wrote:
>
> On Wed, 8 Jun 2022 at 18:12, Dave wrote:
>
>> I tried the but it doesn’t seem to work?
>> myCompareFile1 = ascii(myTitleName)
>> myCompareFile1.replace("\u2019", "'")
>
> Strings in Python are immutable. When you call ascii(), you get back a
> new string, but it's one that has actual backslashes and such in it.
> (You probably don't need this step, other than for debugging; check
> the string by printing out the ASCII version of it, but stick to the
> original for actual processing.) The same is true of the replace()
> method; it doesn't change the string, it returns a new string.
>
>>>> word = "spam"
>>>> print(word.replace("sp", "h"))
> ham
>>>> print(word)
> spam
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi,
I misunderstood how it worked, basically I’ve added this function:
def filterCommonCharacters(theString):
myNewString = theString.replace("\u2019", "'")
return myNewString
Which returns a new string replacing the common characters.
This can easily be extended to include other characters as and when they come
up by adding a line as so:
myNewString = theString.replace("\u2014", “]” #just an example
Which is what I was trying to achieve.
All the Best
Dave
> On 8 Jun 2022, at 11:17, Chris Angelico wrote:
>
> On Wed, 8 Jun 2022 at 19:13, Dave wrote:
>>
>> Hi,
>>
>> Thanks for this!
>>
>> So, is there a copy function/method that returns a MutableString like in
>> objective-C? I’ve solved this problems before in a number of languages like
>> Objective-C and AppleScript.
>>
>> Basically there is a set of common characters that need “normalizing” and I
>> have a method that replaces them in a string, so:
>>
>> myString = [myString normalizeCharacters];
>>
>> Would return a new string with all the “common” replacements applied.
>>
>> Since the following gives an error :
>>
>> myString = 'Hello'
>> myNewstring = myString.replace(myString,'e','a’)
>>
>> TypeError: 'str' object cannot be interpreted as an integer
>>
>> I can’t see of a way to do this in Python?
>>
>
> Not sure why you're passing the string as an argument as well as using
> it as the object you're calling a method on. All you should need to do
> is:
>
> myString.replace('e', 'a')
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
> On 8 Jun 2022, at 11:25, Dave wrote:
>
>myNewString = theString.replace("\u2014", “]” #just an example
Opps! Make that
myNewString = myNewString.replace("\u2014", “]” #just an example
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi, This is a tool I’m using on my own files to save me time. Basically or most of the tracks were imported with different version iTunes over the years. There are two problems: 1. File System characters are replaced (you can’t have ‘/‘ or ‘:’ in a file name). 2. Smart Quotes were added at some point, these need to replaced. 3. Other character based of name being of a non-english origin. If find others I’ll add them. I’m using MusicBrainz to do a fuzzy match and get the correct name. it’s not perfect, but works for 99% of files which is good enough for me! Cheers Dave > On 8 Jun 2022, at 18:23, Avi Gross via Python-list > wrote: > > Dave, > > Your goal is to compare titles and there can be endless replacements needed > if you allow the text to contain anything but ASCII. > > Have you considered stripping out things instead? I mean remove lots of stuff > that is not ASCII in the first place and perhaps also remove lots of extra > punctuation likesingle quotes or question marks or redundant white space and > compare the sort of skeletons of the two? > > And even if that fails, could you have a measure of how different they are > and tolerate if they were say off by one letter albeit "My desert" matching > "My Dessert" might not be a valid match with one being a song about an arid > environment and the other about food you don't need! > > Your seemingly simple need can expand into a fairly complex project. There > may be many ideas on how to deal with it but not anything perfect enough to > catch all cases as even a trained human may have to make decisions at times > and not match what other humans do. We have examples like the TV show > "NUMB3RS" that used a perfectly valid digit 3 to stand for an "E" but yet is > often written when I look it up as NUMBERS. You have obvious cases where > titles of songs may contain composite symbols like "œ" which will not compare > to one where it is written out as "oe" so the idea of comparing is quite > complex and the best you might do is heuristic. > > UNICODE has many symbols that are almost the same or even look the same or > maybe in one font versus another. There are libraries of functions that allow > some kinds of comparisons or conversions that you could look into but the > gain for you may not be worth it. Nothing stops a person from naming a song > any way they want and I speak many languages and often see a song re-titled > in the local language and using the local alphabet mixed often with another. > > Your original question is perhaps now many questions, depending on what you > choose. You started by wanting to know how to compare and it is moving on to > how to delete parts or make substitutions or use regular expressions and it > can get worse. You can, for example, take a string and identify the words > within it and create a regular expression that inserts sequences between the > words that match any zero or one or more non-word characters such as spaces, > tabs, punctuation or non-ASCII, so that song titles with the same words in a > sequence match no matter what is between them. The possibilities are endless > but consider some of the techniques that are used by some programs that parse > text and suggest alternate spellings or even programs like Google Translate > that can take a sentence and then suggest you may mean a slightly altered > sentence with one word changed to fit better. > > You need to decide what you want to deal with and what will be mis-classified > by your program. Some of us have suggested folding the case of the words but > that means asong about a dark skinned person in Poland called "Black Polish" > would match a song about keeping your shoes dark with "black polish" so I > keep repeating it is very hard or frankly impossible, to catch every case I > can imagine and the many I can't! > > But the emphasis here is not your overall problem. It is about whether and > how the computer language called python, and perhaps some add-on modules, can > be used to solve each smaller need such as recognizing a pattern or replacing > text. It can do quite a bit but only when the specification of the problem is > exact. > > > > > -Original Message- > From: Dave > To: [email protected] > Sent: Wed, Jun 8, 2022 5:09 am > Subject: Re: How to replace characters in a string? > > Hi, > > Thanks for this! > > So, is there a copy function/method that returns a MutableString like in > objective-C? I’ve solved this problems before in a number of languages like > Objective-C and AppleScript. > > Basically there is a set of common char
Re: How to test characters of a string
Hi,
I’ve found you also need to take care of multiple disk CD releases. These have
a format of
“1-01 Track Name”
“2-02 Trackl Name"
Meaning Disk 1 Track1, Disk 2, Track 2.
Also A and B Sides (from Vinyl LPs)
“A1-Track Name”
“B2-Track Name”
Side A, Track 1, etc.
Cheers
Dave
> On 8 Jun 2022, at 19:36, Dennis Lee Bieber wrote:
>
> On Wed, 8 Jun 2022 01:53:26 + (UTC), Avi Gross
> declaimed the following:
>
>
>>
>> So is it necessary to insist on an exact pattern of two digits followed by a
>> space?
>>
>>
>> That would fail on "44 Minutes", "40 Oz. Dream", "50 Mission Cap", "50 Ways
>> to Say Goodbye", "99 Ways to Die"
>>
>> It looks to me like you need to compare TWICE just in case. If it matches in
>> the original (perhaps with some normalization of case and whitespace, fine.
>> If not will they match if one or both have something to remove as a prefix
>> such as "02 ". And if you are comparing items where the same song is in two
>> different numeric sequences on different disks, ...
>
> I suspect the OP really needs to extract the /track number/ from the
> ID3 information, and (converting to a 2digit formatted string) see if the
> file name begins with that track number... The format of the those
> filenames appear to be those generated by some software when ripping CDs to
> MP3s -- for example:
>
> -=-=-
> c:\Music\Roger Miller\All Time Greatest Hits>dir
> Volume in drive C is OS
> Volume Serial Number is 4ACC-3CB4
>
> Directory of c:\Music\Roger Miller\All Time Greatest Hits
>
> 04/11/2022 05:06 PM .
> 04/11/2022 05:06 PM ..
> 07/26/2018 11:20 AM 4,493,279 01 Dang Me.mp3
> 07/26/2018 11:20 AM 5,072,414 02 Chug-A-Lug.mp3
> 07/26/2018 11:20 AM 4,275,844 03 Do-Wacka-Do.mp3
> 07/26/2018 11:20 AM 4,284,208 04 In the Summertime.mp3
> 07/26/2018 11:20 AM 6,028,730 05 King of the Road.mp3
> 07/26/2018 11:20 AM 4,662,182 06 You Can't Roller Skate in a
> Buffalo Herd.mp3
> 07/26/2018 11:20 AM 5,624,704 07 Engine, Engine #9.mp3
> 07/26/2018 11:20 AM 5,002,492 08 One Dyin' and a Buryin'.mp3
> 07/26/2018 11:21 AM 6,799,224 09 Last Word in Lonesome Is Me.mp3
> 07/26/2018 11:21 AM 5,637,230 10 Kansas City Star.mp3
> 07/26/2018 11:21 AM 4,656,910 11 England Swings.mp3
> 07/26/2018 11:21 AM 5,836,638 12 Husbands and Wives.mp3
> 07/26/2018 11:21 AM 5,470,216 13 I've Been a Long Time Leavin'.mp3
> 07/26/2018 11:21 AM 6,230,236 14 Walkin' in the Sunshine.mp3
> 07/26/2018 11:21 AM 6,416,060 15 Little Green Apples.mp3
> 07/26/2018 11:21 AM 9,794,442 16 Me and Bobby McGee.mp3
> 07/26/2018 11:22 AM 7,330,642 17 Where Have All the Average People
> Gone.mp3
> 07/26/2018 11:22 AM 7,334,752 18 South.mp3
> 07/26/2018 11:22 AM 6,981,924 19 Tomorrow Night in Baltimore.mp3
> 07/26/2018 11:22 AM 9,353,872 20 River in the Rain.mp3
> 20 File(s)121,285,999 bytes
> 2 Dir(s) 295,427,198,976 bytes free
>
> c:\Music\Roger Miller\All Time Greatest Hits>
> -=-=-
>
> Untested (especially the ID3 "variable" -- substitute variables as
> needed to match the original code):
>
>>>> id3Track = 2
>>>> track_number = "%2.2d " % id3Track
>>>> track_number
> '02 '
>>>> filename = "02 This is the life.mp3"
>>>> if filename.startswith(track_number):
> ... nametitle = filename[3:]
> ... else:
> ... nametitle = filename
> ...
>>>> if nametitle.endswith(".mp3"):
> ... nametitle = nametitle[:-4]
> ...
>>>> nametitle
> 'This is the life'
>
> Handling ASCII ' and " vs Unicode "smart" quotes is a different matter.
>
> One may still run the risk of having a filename without a track number
> BUT having a number that just manages to match the track number. To account
> for that I'd suggest using the sequence:
>
> * Strip extension (if filename.lower().endswith(".mp3"): ...)
> * Handle any Unicode/ASCII quotes in both filename AND ID3 track title
> * Compare filename and title.
> * IF MATCHED -- done
> * IF NOT MATCHED
> * Format ID3 track number as shown above
> * Compare filename to (formatted track number + track
> title)
> * IF MATCHED -- done
> * IF NOT MATCHED
> * Log full filename and ID3 track
> title/track number to a
> log for later examination.
>
>
>
> --
> Wulfraed Dennis Lee Bieber AF6VN
> [email protected]://wlfraed.microdiversity.freeddns.org/
> --
> https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Function to Print a nicely formatted Dictionary or List?
Hi, Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? By nicely formatted I mean not all on one line! Cheers Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Function to Print a nicely formatted Dictionary or List?
Hi,
I quite like the format that JSON gives - thanks a lot!
Cheers
Dave
> On 9 Jun 2022, at 20:02, Stefan Ram wrote:
>
> Since nicety is in the eyes of the beholder, I would not
> hesitate to write a custom function in this case. Python
> has the standard modules "pprint" and "json".
>
> main.py
>
> import json
> d ={ 1:2, 'alpha': 'beta' }
> print( json.dumps( d, indent=4 ))
>
> output
>
> {
>"1": 2,
>"alpha": "beta"
> }
>
--
https://mail.python.org/mailman/listinfo/python-list
Kivy native GUI examples
I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Kivy native GUI examples
On 1/7/19 11:14 AM, Thomas Jollans wrote: On 07/01/2019 15.51, Dave wrote: I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? AFAIK looking like a native app is quite simply not something Kivy helps you with. If that's important, you should look into other options such as Qt (PyQt5 or PySide2). -- Thomas Thanks Thomas. -- https://mail.python.org/mailman/listinfo/python-list
System printer object
I need to print to one or both of my system printers. I have not found a printer object in Python or in Tkinter. This needs to work with Linux, Window, and Mac. Can someone point me in the right direction? Ultimately, I want to have a File/Print in the menu that lets me select the printer and properties. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
preferences file
I'm doing a small application and want to add user preferences. Did some googling to see if there are standard Python ways/tools, but it seems not so much. My specific questions are: 1. Best practices for a user preference file/system? 2. File format favored and why - ini, JSON, etc? 3. File location? I'm using Ubuntu and I believe that the correct location would be home/.config/ . What about Mac and Windows? Would like to find a Python library that handles all of this, but so far... Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
Sorry about the duplicate messages - bad hair day! Dave, On 2/27/19 10:38 AM, Dave wrote: On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 2/27/19 11:38 AM, Rhodri James wrote: On 27/02/2019 15:37, Dave wrote: * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. This requirement will cause you endless pain, particularly when mobiles enter the picture. I'm not convinced it's a completely good idea; a sensible UI for a desktop probably won't be sensible for a phone and vice versa Agreed - that is why I'm open to two GUI kits. Dave -- https://mail.python.org/mailman/listinfo/python-list
configparser - which one?
I use Python3 3, and expected learning how to use configparser would be
no big deal. Well! Seems there is configparser, stdconfigparser, and
safeconfigparser, and multiple ways to set the section and entries to
the section. A little confusing. I want to future-proof may code, so
what should I be using?
As for setting the sections and entries, the following both work.
from configparser import ConfigParser # Python 3 syntax
parser = ConfigParser()
parser['DEFAULT'] = {'Language': 'English',
'Units': 'English',
'UseDefaults': 'True',
'NumberRidesDisplay': '30',
'Pi': '3.14'}
parser.add_section('Default')
parser.set('default', 'language', 'english')
parser.set('default', 'units_measure', 'english')
parser.set('default', 'background_color', 'white')
parser.set('default', 'useDefaults', 'true')
parser.set('default', 'numToDisp', '12')
parser.set('default', 'pi', '3.14')
The advantage of the former is that it will handle 'DEFAULT', while the
last one won't. I like the former, but not sure if it is the future.
Thanks,
Dave
--
https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/25/19 10:58 PM, DL Neil wrote: Dave, On 26/03/19 1:10 PM, Dave wrote: I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? (with apologies for not answering the question directly) After striking this problem, I was encouraged to take a look at JSON, and thence YAML. Once there, as they say, didn't look back! - multi-dimensional possibilities, cf .ini - similarity/correspondence with Python data structures - convenient PSL - easily adopted by (power-)users, cf Python code WebRefs: - similar Q: https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python - article: https://martin-thoma.com/configuration-files-in-python/ - similar discussion: https://stackoverflow.com/questions/3085029/pros-and-cons-for-different-configuration-formats Wish I could do that. Customer wants .ini. I would need to sell them on an alternative. The issue is human readable - .ini is easier for people to understand. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/26/19 4:29 AM, Terry Reedy wrote:
On 3/25/2019 8:10 PM, Dave wrote:
I use Python3 3, and expected learning how to use configparser would
be no big deal. Well! Seems there is configparser, stdconfigparser, and
configparser is what IDLE uses. I would read the extra or deleted
features of the others and see if they apply to your client's project.
safeconfigparser, and multiple ways to set the section and entries to
the section. A little confusing. I want to future-proof may code, so
what should I be using?
As for setting the sections and entries, the following both work.
from configparser import ConfigParser # Python 3 syntax
parser = ConfigParser()
parser['DEFAULT'] = {'Language': 'English',
'Units': 'English',
'UseDefaults': 'True',
'NumberRidesDisplay': '30',
'Pi': '3.14'}
The dict interface is newer but I doubt that the older one will go away.
(IDLE uses it because it predates the dict interface. Since this code
is pretty static, I do not currently see a payoff for conversion.)
parser.add_section('Default')
parser.set('default', 'language', 'english')
parser.set('default', 'units_measure', 'english')
parser.set('default', 'background_color', 'white')
parser.set('default', 'useDefaults', 'true')
parser.set('default', 'numToDisp', '12')
parser.set('default', 'pi', '3.14')
The advantage of the former is that it will handle 'DEFAULT', while
the last one won't. I like the former, but not sure if it is the future.
We do not remove things and break backwards compatibility lightly.
Thanks everyone. So, I'll use configparser, but I do like the
dictionary API as it makes the code a little easier as I can pass as
arguments a section name and a dictionary with the contents to a
function to write the complete section.
Dave,
--
https://mail.python.org/mailman/listinfo/python-list
How call method from a method in same class?
As classes get more complex, it is good to call a function to do some of
the processing, and make the code easier to follow. My question is how
to do that? I've attached some silly code to illustrate the point. The
error is: name 'validScale' is not defined. Well, yes it is, but maybe
not the correct way. Suggestions?
Dave,
class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale. For example: 32, F, C will return
0 degrees C
"""
def __init__(self, temperature, scale, newScale):
self.temperature = temperature
self.scale = scale
self.newScale = newScale
def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False
def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
if validScale(self.newScale):
newScaleValid = True
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)
if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
--
https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:12 PM, Irv Kalb wrote:
On Apr 1, 2019, at 7:02 PM, Dave wrote:
As classes get more complex, it is good to call a function to do some of the
processing, and make the code easier to follow. My question is how to do that?
I've attached some silly code to illustrate the point. The error is: name
'validScale' is not defined. Well, yes it is, but maybe not the correct way.
Suggestions?
Dave,
class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale. For example: 32, F, C will return
0 degrees C
"""
def __init__(self, temperature, scale, newScale):
self.temperature = temperature
self.scale = scale
self.newScale = newScale
def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False
def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
if validScale(self.newScale):
newScaleValid = True
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)
if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
--
https://mail.python.org/mailman/listinfo/python-list
To answer your specific question, you call a method in the same class by
calling: self.methodName For example: self.validScale
However, once you fix that, you wind find that the if statement in that method
is not built correctly.
Also, since the variable self.scale is already set in your __init__ method,
there is no need to pass it into your function. You could just use self.scale
inside that method.
Irv
Irv,
Thanks for the response! I realize the code is junk - just done to
illustrate the problem.
Dave,
--
https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:02 PM, Dave wrote:
As classes get more complex, it is good to call a function to do some of
the processing, and make the code easier to follow. My question is how
to do that? I've attached some silly code to illustrate the point. The
error is: name 'validScale' is not defined. Well, yes it is, but maybe
not the correct way. Suggestions?
Dave,
class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale. For example: 32, F, C will return
0 degrees C
"""
def __init__(self, temperature, scale, newScale):
self.temperature = temperature
self.scale = scale
self.newScale = newScale
def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False
def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
if validScale(self.newScale):
newScaleValid = True
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)
if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
Thanks all for your (ready, wait for it) self-lessness help (get it?)
Dave (laughing)
--
https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:29 PM, Cameron Simpson wrote:
On 01Apr2019 22:02, Dave wrote:
As classes get more complex, it is good to call a function to do some
of the processing, and make the code easier to follow. My question is
how to do that? I've attached some silly code to illustrate the
point. The error is: name 'validScale' is not defined. Well, yes it
is, but maybe not the correct way. Suggestions?
It is and it isn't. See below:
class TempConverter():
""" Temperature Converter converts a tempeature from one scale
to another scale. For example: 32, F, C will return
0 degrees C
"""
[...]
def validScale(self, scaleName):
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False
def convertTemp(self):
""" Converts temperature scale if scales valid."""
if validScale(self.scale):
scaleValid = True
[...]
It is an instance method, so:
if self.validScale(self.scale)
would resolve the name. However, there are several things worth
discussing here.
First up, validScale itself returns a Boolean, so just return the test
result. Change:
if scaleName.upper == 'F' or 'C' or 'K':
return True
else:
return False
into:
return scaleName.upper == 'F' or 'C' or 'K'
Second, the condition is buggy. You want this:
return scaleName.upper() in ('F', 'C', 'K')
i.e. you need to call (the "()") the .upper method, and you need to
check if the result is in your collection of valid results.
This expression:
value == A or B or C
means: True if value == A, otherwise B if B is true, otherwise C.
The next thing to observe is that you're testing whether self.scale is
valid. Normal practice would be to make that test in __init__, and raise
a ValueError if it is not so:
def __init__(self, .scale...):
if scale.upper() not in ('F', 'C', 'K'):
raise ValueError("invalid scale %r: expected one of F, C or K" %
(scale,))
why recite the scale in the message? Because it makes the offending
value obvious. In particular, if for example you called this incorrectly
and had the temperature in there instead of the scale that will be
trivial to debug from the message.
Of course, you actually want to be able to test any scal evalue for
validity, not just the one stuffed into your instance (.scale). So lets
revisit the validScale method:
def validScale(self, scale):
return scaleName.upper() in ('F', 'C', 'K')
You'll notice that it doesn't depend in "self". Or, for that matter, the
class. So this is a "static" method: a function defined in the class for
conceptual clarity, but not with any dependence on the class itself or a
particular class instance. So:
@staticmethod
def validScale(scale):
return scaleName.upper() in ('F', 'C', 'K')
In __init__, and elsewhere, you can still call this from the instance:
def __init__(self, .scale...):
if not self.validScale(scale):
raise ValueError("invalid scale %r: expected one of F, C or K" %
(scale,))
You can also call this from _outside_ the class, for example for other
validation:
scale = input("Enter a temperate scale name (F, C or K): ")
if not TempConverter.validScale(scale):
print("Bad! Bad user!")
newScaleValid = True
Again, validScale returns a Boolean. So you could have just gone:
newScaleValid = self.validScale(newScale)
if scaleValid and newScaleValid:
print('Scale converted')
else:
msg = "There was and error with the scales entered.\n"
msg = msg + "You entered: " + self.scale
msg = msg + ' ' 'and' + self.newScale
print(msg)
if __name__ == "__main__":
myclass = TempConverter(32, 'f', 'c')
myclass.convertTemp()
My personal inclination would be do define a Temperature class with a
convert function to be used like this:
temp = Temperature(32, 'f')
tempC = temp.convert('c')
This reduces the complexity of the class and IMO makes it easier to use
elsewhere.
BTW, you get an instance back from tempConverter(...), not a class. So
don't call it "myclass".
Cheers,
Cameron Simpson
Cameron,
I'm going to need a while to work through this. As I mentioned, this
was quick and dirty code just to illustrate a point - not intended to be
good code. So I'll take a close read tomorrow. Thanks again!!
Dave,
--
https://mail.python.org/mailman/listinfo/python-list
Python best practice instantiating classes in app
As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, but may not be the best way to do the job. A slight variation is to do this in the main module, but the main module has to be imported into the others. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. So what are the suggestions from people that have been down this road before? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Python best practice instantiating classes in app
On 4/29/19 3:26 PM, Terry Reedy wrote: On 4/29/2019 1:38 PM, Dave wrote: As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, You can have one *or more* such modules. Perhaps you already do. but may not be the best way to do the job. In what way do you consider it unsatisfactory. It is not that I consider it unsatisfactory as much as I'm looking for the best way. I am constantly amazed at the thought that has been given to this language (with the exception of access modifiers - perhaps, and lack of a case statement), and often find that there is a better way of doing everything. A slight variation is to do this in the main module, but the main module has to be imported into the others. Avoid import loops unless really necessary. They often work, but when they don't ... its a pain. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. Right. -- https://mail.python.org/mailman/listinfo/python-list
Python's Performance
Hello All, I would like to gather some information on Python's runtime performance. As far as I understand, it deals with a lot of string objects. Does it require a lot string processing during program execution? How does it handle such time-consuming operations? Is there a way to find out how many string operations (perhaps in the underlying system) ) it does during program execution? Thanks a lot for your help! Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- http://mail.python.org/mailman/listinfo/python-list
Re: Python's Performance
Yes, I would like to know how many internal string operations are done inside the Python interpreter. Thanks. Laszlo Zsolt Nagy <[EMAIL PROTECTED]> wrote: Dave wrote:> Hello All,> > I would like to gather some information on Python's runtime > performance. As far as I understand, it deals with a lot of string > objects. Does it require a lot string processing during program > execution? How does it handle such time-consuming operations? Is there > a way to find out how many string operations (perhaps in the > underlying system) ) it does during program execution?Do you want to know how many internal string operations are done inside the Python interpreter? I believe it is not a useful information. There are benchmarks testing the *real performance* of Python.For example: http://www.osnews.com/story.php?news_id=5602Les Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- http://mail.python.org/mailman/listinfo/python-list
Python name lookups
Hello All, As far as I understand, Python deals with a lot of string objects, i.e. it looks up all names. Is there a way to find out how many name lookup operations take place in a Python program? Is it the name lookup operation or hash operation that degrades performance? What function does Python use for name lookup operations? Is it the lookdict function in Objects/dictobject.c? Thank you for your help! __ Start your day with Yahoo! - Make it your home page! http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Profiling Python using gprof
Hello, I would like to profile a Python program using gprof. I already rebuilt Python with CC="gcc -pg" ./configure. So, I should be able to use gprof. How do I do that? Should I first run Python and then gprof? What are the steps? Thanks a lot! __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python name lookups / Interning strings
--- [EMAIL PROTECTED] wrote: > lookdict_string is used for most lookups of the form > obj.attr > because they are never found to have non-string keys > entered or searched. > > Furthermore, most of these string keys are > "interned", > which I believe makes the check > if (ep->me_key == NULL || ep->me_key == key) > return ep; > return a result without comparing the contents of > the strings. What exactly does it mean to "intern" a string? Thanks! __ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ -- http://mail.python.org/mailman/listinfo/python-list
Profiling results
Hello All, I'm trying to profile a Python program using gprof, but I don't understand some of the results, especially what some of the functions do. For example, _moncount, mcount, _PyEval_EvalFrame take too much time. What are they for? Any ideas? Thank you for your help! __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
gprof results
Hello All, I googled to find an answer for my question, but had no luck. I'm trying to profile a Python program using gprof, but I don't understand what _moncount and mcount are. I couldn't find their source code under Python source tree. moncount takes about 30% of my program... What are _moncount and mcount for? Are they functions or variables? Any ideas? Thank you for your help! __ Yahoo! Music Unlimited Access over 1 million songs. Try it free. http://music.yahoo.com/unlimited/ -- http://mail.python.org/mailman/listinfo/python-list
Hashing Function
Hello All, I'm wondering what hashing function Python uses for dictionaries. Thanks for your help. Dave __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Idle.pyw doesn't start in 2.4.1
Hi, I installed 2.4.1 on both my wife's & my computer. Her idle (pyw) starts fine, but mine doesn't. I have had previous versions on my computer as well as idlefork, but I removed them before installing 2.4.1. I tried uninstalling and reinstalling several times, and my idle.pyw file does not respond. When I click the idle.py file, it starts a console with the following error message printed 13 times: Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'test'. returning default value: '#ff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'test'. returning default value: '#00' Then it boots a blank idle window with white menus. My wife's pull-down menus are gray. I don't know if the color is a clue to anything or not. Anyone else have this problem, know why it happened, or know how to solve it? Yes, I could just use the idle that boots with idle.py, but I'm just wondering why her install produced a clean working version and my install came with this bug? Thanks -Dave -- http://mail.python.org/mailman/listinfo/python-list
Plugin system; imp module head scratch
Hi, all,
I'm trying to implement a simple plugin framework, with some
unexpected results. I'm using Python 2.3.4 on Windows 2000.
My script loader.py loads plugin packages from a directory (in this
case its own), and checks a variable defined in the package's
__init__.py for information on the plugin.
The directory in which loader.py sits is itself a package::
plugin_test
|
+ Plugin1
||
|__init__.py
|
__init__.py
loader.py
I must be misunderstanding how the imp module works, or something.
Although the correct package is returned by my helper method, its
member variables are those of the the parent package, plugin_test.
The output of this demo is::
Directory plugin_test
Which seems contradictory. What have I got wrong?
Best Regards,
Dave
This is plugin_test/Plugin1/__init__.py::
dir = "plugin_test/Plugin1"
This is plugin_test/__init__.py::
dir = "plugin_test"
And here is the loader script, plugin_test/loader.py::
import os
import imp
def GetPackage(name, peerFile, relPath = '.'):
"""
Return the named Python package on a
relative path from the file given
"""
path = os.path.normpath(
os.path.join(os.path.dirname(peerFile), relPath))
try:
fObj, path, descr = imp.find_module(name, [path])
except ImportError:
return None
if descr[2] != imp.PKG_DIRECTORY:
return None
try:
return imp.load_module(name, None, '', descr)
except:
return None
if __name__ == "__main__":
pkg = GetPackage("Plugin1", __file__, '.')
print pkg
print "Directory ", pkg.dir
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with an 8th grade science project
On Thursday, November 20, 2014 1:48:06 PM UTC-7, Ian wrote: > On Thu, Nov 20, 2014 at 1:13 PM, Dave Angel wrote: > > > >> 1. In the factorial() function we call the CPU_Percent() function and > >> write the CPU utilization value to a file. > >> - Is this a correct value or will the CPU utilization below lower because > >> the factorial() function made its calculation and is now just checking the > >> CPU utilization? > > > > I'm not familiar with that package; I just took a quick look at > > pypi. So I'd have to guess. But since your timing is so huge, I'd > > guess that you're measuring utilization during a time period that > > your factorial calculation is paused. In other words you're > > measuring cpu utilization for the other processes in your > > system. > > > > Probably someone else will correct me, but I'd guess you need to > > measure utilization with a separate process. > > I'm not familiar with it either, but I would guess that it's probably > just pulling data from /proc/stat. The data is not going to be any > different if pulled from one process versus another. However, the time > that is spent waiting for this data could skew the results if done a > lot, so I suggest doing it only once at the end of the factorial > function rather than on every iteration of the factorial loop. > > If you want multiple measurements while the function is running, then > either check it only every X iterations, or run a separate process and > check it every 100 milliseconds or so. The latter is probably > preferable since the time between iterations will depend on the system > and will also get progressively slower for large factorials. All, thanks for all of the advice. I took the function call to measure CPU usage out of the loop and now get very fast responses. For example execution time for 1 is 0.46 seconds and for 10 is 0.0082 seconds. I took a quick look at subprocesses to run the cpu function simultaneously with the factorial function or maybe we can figure out a way to use something like top and filter out CPU while we run the factorial program. Anyway, thanks for all of the help and the sanity check on the times I was getting. Best regards, Dave -- https://mail.python.org/mailman/listinfo/python-list
tkinter
http://forums.devshed.com/python-programming-11/setting-tkinter-checkbox-default-graphical-state-865148.html Please answer this question I failed to resolve. Thanks, Dave. -- http://mail.python.org/mailman/listinfo/python-list
Interned Strings
Hello All, I'm trying to clarify how Python avoids byte by byte string comparisons most of the time. As I understand, dictionaries keep strings, their keys (hash values), and caches of their keys. Caching keys helps to avoid recalculation of a string's hash value. So, when two strings need to be compared, only their cached keys are compared, which improves performance as there is no need for byte by byte comparison. Also, there is a global interning dictionary that keeps interned strings. What I don't understand is why strings are interned. How does it help with string comparisons? Thank you. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Memory Profiler
Hi, Is there any memory profiler for Python programs? I would like to see how much memory objects take up, cache misses, etc. I tried to patch PySizer, but got a build error (Error 138). Thanks! __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Announcing Switch, the CSS Preprocessor!
Powered by Mod_Python, Switch CSS is a full featured, production ready
CSS preprocessor.
Some of the features include:
- variables
- constants
- selector prepending:
#selector {
.class { property: value; }
}
outputs:
#selector { }
#selector .class { property: value; }
With unlimited levels of nesting, this makes CSS easy to read and fast
to write.
- selector copying:
#selector { width: 200px; }
#other_selector { @copy #selector; }
outputs:
#selector { width: 200px; }
#other_selector { width: 200px; }
- selector inheritance:
#selector { width: 200px; }
#other_selector { @inherit #selector; }
outputs:
#other_selector,
#selector { width: 200px; }
#other_selector { }
There are other features, also. I think that's enough to get people
excited.
Switch was designed as a production-ready tool to solve the problem of
front-end design with CSS based-layouts and large CSS files. As we
realized we had 40,000 lines of CSS written and no means of abstracting
or managing the code easily, we decided to write a preprocessor that
was easy to use and had all the bells and whistles a CSS designer could
ever want.
We originally approached the program using PHP. When it took the PHP
version 30 seconds to process one CSS file, we knew PHP wasn't going to
cut it. By re-implementing the appication in Python - using a literal,
1-1 translation of the PHP version, under mod_python, Switch was able
to process the same file in under 1/4 of a second.
YAY! PYTHON!
The sourceforge project link follows. We could really use some tire
kickers... This group was invaluable in the early development process,
so we're announcing it officially here, and on mod_python first.
https://sourceforge.net/projects/switchcss/
Thanks,
Dave Worley
--
http://mail.python.org/mailman/listinfo/python-list
Re: Announcing Switch, the CSS Preprocessor!
It's not tied deeply to mod_python.
The processor works like this:
You create an "sss" file, using Switch specific features. Then, you
place the file under Apache/mod_python OR you can use the command-line
Switch tool to process the SSS file and output a CSS file. In this way,
it works very similar to an XSLT transformation in that you write using
a shorthand method that outputs to a more verbose, crystallized file.
This way, it's platform agnostic. I'm also kicking around the idea of a
GUI tool.
The reason we didn't give it the ability to "preprocess if changed" is
because we're looking forward to implementing a system that can handle
conditional statements:
if $BROWSER is IE and $BROWSER_VERSION > 6 {
/* output this */
} else {
/* output this */
}
This would need to be compiled with every request. Maybe, though, we
could have different settings in which you could compile with every
request, compile on change, or precompile...
Actually, it's an open source program. Hack away!
Sybren Stuvel wrote:
> Dave enlightened us with:
> > Powered by Mod_Python, Switch CSS is a full featured, production
> > ready CSS preprocessor.
>
> It sounds very nice! Really something I could use!
>
> In how far is it coupled with mod_python? I'd rather not re-preprocess
> my CSS on every request. IMO it would be nice if the preprocess step
> could be done only if the source CSS changes. But hey, maybe you've
> already done that.
>
> Does it integrate or live next to Django well?
>
> Sybren
> --
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?
> Frank Zappa
--
http://mail.python.org/mailman/listinfo/python-list
missing has_column_major_storage
hello I have intalled the Enthought Edition 1.0.0, when i successed use f2py compile my fortran file to python module. But when I call "has_column_major_storage function" in the extended module. it's cannot find. "has_column_major_storage function" function have been remove from numpy/f2py ?? how can i change the array storage C to Fortran type?? thanks -- http://mail.python.org/mailman/listinfo/python-list
HTML Encoded Translation
How can I translate this: gi to this: "gi" I've tried urllib.unencode and it doesn't work. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML Encoded Translation
Got it, great. This worked like a charm. I knew I was barking up the
wrong tree with urllib, but I didn't know which tree to bark up...
Thanks!
Fredrik Lundh wrote:
> Dave wrote:
>
> > How can I translate this:
> >
> > gi
> >
> > to this:
> >
> > "gi"
>
> the easiest way is to run it through an HTML or XML parser (depending on
> what the source is). or you could use something like this:
>
> import re
>
> def fix_charrefs(text):
> def fixup(m):
> text = m.group(0)
> try:
> if text[:3] == "&#x":
> return unichr(int(text[3:-1], 16))
> else:
> return unichr(int(text[2:-1]))
> except ValueError:
> pass
> return text # leave as is
> return re.sub("&#?\w+;", fixup, text)
>
> >>> fix_charrefs("gi")
> 'gi'
>
> also see:
>
> http://effbot.org/zone/re-sub.htm#strip-html
>
> > I've tried urllib.unencode and it doesn't work.
>
> those are HTML/XML character references, not encoded URL characters.
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Need some help here
The money's on the way! "Kareem840" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello. Unfortunately, I am in need of money to pay my credit card > bills. If you could spare just $1, I would be grateful. I have a Paypal > account. [EMAIL PROTECTED] I swear this will go to my card > balances. Thank you. > -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation Help!
OK, I'm stumped. I'm trying to find newline characters (\n, specifically) that are NOT in comments. So, for example (where "<-" = a newline character): == 1: <- 2: /*<- 3: --<- 4: comment<- 5: --<- 6: */<- 7: <- 8: CODE CODE CODE<- 9: <- == I want to return the newline characters at lines 1, 6, 7, 8, and 9 but NOT the others. I've tried using regular expressions but I dislike them because they aren't immediately readable (and also I don't bloody understand the things). I'm not opposed to using them, though, if they provide a solution to this problem! Thanks in advance for any suggestions anyone can provide. - Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
This is great, thanks! -- http://mail.python.org/mailman/listinfo/python-list
stumped by tricky logic
So I'm trying to write a CSS preprocessor.
I want to add the ability to append a selector onto other selectors.
So, given the following code:
=
#selector {
{ property: value; property: value; }
.other_selector { property: value; property: value; }
#selector_2 {
.more_selector { property: value; }
}
}
=
I want to return the following:
=
#selector { property: value; property: value; }
#selector .other_selector { property: value; property: value; }
#selector #selector_2 .more_selector { property: value; }
=
What I think I need to do is match the "{" character with its "}" pair,
then see if there's another "{" before a matching "}" - but that's
about as far as my brain will go. The actually code to make this
actually happen is not coming out when I type.
Any suggestions would be very appreciated. And handsomely rewarded (by
karma, not me).
- Dave
--
http://mail.python.org/mailman/listinfo/python-list
Re: Server side newbie
Check out mod_python for Apache. Basically, you would write your python app as a server-side script and the end user would interact with your code via a webpage. It's likely that you won't need any GUI code you wrote, as HTML form elements will be your choices in the browser. Check out PSP: it enables you to mix Python code with an otherwise ordinary HTML page. Mod_Python: http://www.modpython.org/ PSP article: http://www.onlamp.com/pub/a/python/2004/02/26/python_server_pages.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Get System Date?
Dustan, Python has a module called, appropriately, "time". Like most things in Python, it's fairly simple and straightforward to use. The module is documented here: http://docs.python.org/lib/module-time.html Breifly, though, the format you want is built right into time: >>> import time >>> now = time.localtime() >>> print now (2006, 2, 5, 13, 21, 15, 6, 36, 0) So to get the year, month, and day you would just have to manipulate the values returned by time.gmtime(). - Dave -- http://mail.python.org/mailman/listinfo/python-list
translating PHP to Python
Anyone familiar with PHP? I'm trying to make a translation. In PHP you can get the current object's name by going like this: get_class(item) == 'ClassName' I've tried type(item), but since I can't be sure if I'll be in __main__ or as a child object, I can't guarantee what that value will return, so I can't just manipulate that value as a string. Is there a simple way to get the current object's name? You would think __name__ would work, right? It doesn't. Now here's another, similar one: You can reference an object's parent object directly in PHP, like so: //note the charming use of semi-colon. isn't it cute? parent::__construct( $stuffInAWeirdSyntaxThatDoesntMeanAnythingWhenYouReadIt); I'd like to avoid passing a reference to an object's parent in __init__, but is there a built in way in Python to say "You, Parent Object, do ...stuff!" Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
Farshid, This is a great help, thanks. The second point won't work, though, because by parent class I mean, simply, the object that created the current object, *not* the class the current class is based on. So, for example: class A(object): def __init__(self): self.thing = Thing() self.thing.meth() def do_stuff(self): print "Stuff" class Thing(object): def meth(self): #now here's what I WANT self.parent.do_stuff(args) Is there a built in way to do this in Python, or do I have to pass "parent" when I init Thing? Sorry if this is confusing. It confuses me, too. I should have been a carpenter. - Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: translating PHP to Python
So thanks, all for the help. Turns out that the solution is simple enough, as are most solutions in Python: PHP: parent::__construct(args) does translate to the Python: super(ParentClass, self).__init__(args) The example, that of referencing an object's creator object (if that's the technospecificalist terminosity) has to be done by passing a reference to the creator object to the created object. So: class A(object): def create_child(self): self.child = B() self.child.do_stuff(self) class B(object): def do_stuff(self, parent): self.parent = parent if self.parent.__class__.__name__ == 'A': print "I'm a child of an A!" else: print "Well, I'm a motherless child. Does that mean I can kill Macbeth?" (Bonus points for lame, contrived, and sort of offensive Shakespeare reference) The project I'm working on is a CSS preprocessor. Watch this space. It's totally going to be famous. -- http://mail.python.org/mailman/listinfo/python-list
Loop Backwards
This should be simple, but I can't get it:
How do you loop backwards through a list?
For example, in, say, Javascript:
for (var i = list.length - 1; i >=0; i--) {
do_stuff()
}
I mean, I could reverse the list, but I don't want to. I want it to
stay exactly the same, but I want to start at the end and end at the
beginning.
Thanks!
- Dave
--
http://mail.python.org/mailman/listinfo/python-list
Re: Loop Backwards
Thanks! I knew it was simple... -- http://mail.python.org/mailman/listinfo/python-list
Re: DatePart From String
Robert Rawlins - Think Blue thinkbluemedia.co.uk> writes: > I’ve tried using the time.strptime() function without much success so > thought I’d come and ask your advice. > How exactly does it not work?? This works for me: from time import mktime, strptime from datetime import datetime datetime_string = '2007-02-01 00:00:00' datetime_object = datetime.fromtimestamp( mktime(strptime(datetime_string,'%Y-%m-%d %H:%M:%S'))) print datetime_object.year print datetime_object.month print datetime_object.day print datetime_object.hour print datetime_object.minute print datetime_object.second HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Bessel Functions
amit soni gmail.com> writes: > Can anyone tell me what is the exact syntax for to use it. > Thank you,Amit > For example evaluating j1 @ 0 from scipy import special print special.j1(0) HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: view workspace, like in MatLab ?
Stef Mientki mailbox.kun.nl> writes: > > hello, > > is there a function / library / IDE that displays all the user defined > variables, like the workspace in MatLab ? > > thanks, > Stef Mientki Using ipython (which I would highly recommend!) you can use the %whos 'magic' function. This works as follows (with automagic (no % needed) on and pylab imported): In [1]: x = 10 In [2]: y = rand(3) In [3]: z = 'astring' In [4]: whos Variable Type Data/Info --- x int10 y ndarray[ 0.57395635 0.92184657 0.16277339] z strastring In [5]: reset Once deleted, variables cannot be recovered. Proceed (y/[n])? y In [6]: whos Interactive namespace is empty. In [7]: Note: the %reset 'magic' function works like the Matlab clear all command. HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
Public Telnet Server?
Hi there. I'm a beginner at Python and I'm writing my first Python script. It's a text adventure about coffee and mixing drinks and being crazy and such. I keep updating it and want my friends to beta test it for me, but some of them don't have the right version of Python or don't want to get Python at all. Is there an easy way I can set up a public telnet server so they can just telnet the server and play it? If anyone could give me some options and/or advice, I'd really appreciate it! Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Public Telnet Server?
On Aug 12, 2:03 pm, Jorgen Grahn <[EMAIL PROTECTED]> wrote: > On Sat, 11 Aug 2007 15:07:25 -0000, Dave <[EMAIL PROTECTED]> wrote: > > Hi there. I'm a beginner at Python and I'm writing my first Python > > script. It's a text adventure about coffee and mixing drinks and being > > crazy and such. I keep updating it and want my friends to beta test it > > for me, but some of them don't have the right version of Python or > > don't want to get Python at all. Is there an easy way I can set up a > > public telnet server so they can just telnet the server and play it? > > - get yourself a Unix machine with a real, routable IP address > - enable telnet (or better, ssh) access > - create a new user > - make the game this user's login shell, or let her login script > exec the game > - test it out > - distribute address, user name and password to people > > "netcat ... -e the_game" may be another option. > > However, the security implications of this may be serious. You should > assume these people can get local user shell access whenever they feel > like it, and use your machine for evil purposes. I trust my brother > with local access to my machines, and noone else[1]. > > /Jörgen > > [1] Well, his two cats too, but they have never logged in so far. > Probably forgot the password, too. > > -- > // Jorgen Grahn \X/ snipabacken.dyndns.org> R'lyeh wgah'nagl fhtagn! Thanks for the suggestions. I'm actually on Linux and a friend helped me enabled SSH and make the game the login script for a dummy account, but then he was generous enough to let me put it on a spare server of his too. :) As for the py2exe suggestion, I actually just tried that yesterday so now there's a Windows Executable version of the game for friends to try as well. Both versions are available, plus source, from http://thegriddle.net/python/ if you want to check it out. Thanks again! Dave -- http://mail.python.org/mailman/listinfo/python-list
which Python ? asks beginner
Have given up Java. Want to switch to Python. But _which_ ? There is ver : 2.5 out now 2.6 in beta , final expected Apr 2008 3.0 ? in alpha or beta 3.0 final expected Sep 2008 ? Will the real python please stand up. Thanks, Dave WB3DWE [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Lib for audio?
I need to read microphone input and determine frequency. Is there a lib for that? Thanks, Dave -- http://mail.python.org/mailman/listinfo/python-list
Fast 2D Raster Rendering with GUI
Hi All. I've been formulating in my head a simple image editor. I actually started prototyping is some time ago in Java, but am liking Python more and more. My editor will be nowhere near the level of Gimp/ Photoshop, but I do need fast pixel level control and display. For instance, that means no automatic anti-aliasing and that I will be implementing my own line drawing algorithms. I've got the high level architectual aspects of my program down, but am stuck on what graphics API to use. I want a canvas area of adjustable size which users can draw on with as little lag as possible. The canvas area will be composed of layers (i.e. I require an alpha channel) and I need to be able to zoom in and out of it (zoom levels will be at fixed intervals, so this can be simulated if need be.) I started looking at PyGame but realize that I need to integrate a GUI into the whole thing (or integrate the image into the GUI rather) and I didn't see a straightforward way to do that. Of course, I don't even know if PyGame is the right API for the job anyways :P Any thoughts or ideas that could help me get started? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Fast 2D Raster Rendering with GUI
First I want to say thank you all for your timely replies. This is all good food for thought. I've been programming more many years, but fast graphics rendering is new territory for me. I'm hoping to fine something like a buffer_blit, where I can set all the pixels to change using basic operators, blit them all at once to a pixel buffer, then swap the visible buffer. Ideally it will only change the region of the pixel buffer that needs changing. Because I want layers, I would like to take advantage wherever possible of the available hardware features. I.E. ideally I am hoping that the layers can be textures in memory that get composited in hardware onto the screen. Maybe this is wishful thinking though? I'm also thinking that maybe I can reduce the number of active layers from N down to 3 - the active layer, the layers below it, and the layers above it. Obviously only the active layer needs any sort of sprite-like animations and it on this layer than response time is most important. Having to layer the top layers ontop of it may also play a factor but, as I suggested, I can merge them all together in one time and then use the merged result to layer on top of the active layer. I'm a little nervous about going the C/C++ route. It's been a few years since I used them, I'm new to Python, and jumping into coding Python extensions with C/C++ is not particularly palatable (though I'll do it if I have to.) > Any GUI toolkit will work if you find the low-level access > to their image memory buffers. That's another new step for me. Any ideas where to start? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Quality control in open source development
With the open source licenses that allow redistribution of modified code, how do you keep someone unaffiliated with the Python community from creating his or her own version of python, and declaring it to be Python 2.6, or maybe Python 2.7 without any approval of anyone at the PSF? Maybe their code is terrible, and not even compatible with the rest of Python! How can the PSF, for example, maintain the quality and coheren of new code contributed to be part of Python, or derivative works that claim to be some future version of Python? If licensees can redisribute as they like, isn't this a huge problem? Is this dealt with be restricting use of the Python trademarks? Just curious.. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reg: Installation problems in psycopg2
gmail.com> writes: > I am trying to install psycopg2 in my windows machine for > connecting with the PostgreSQL server. > Since there is no binary executable*, I am trying to build my own > - and I am facing this issue. > > C:\MinGW\bin\..\lib\gcc\mingw32\3.4.5\..\..\..\..\mingw32\bin\ld.exe: > cannot find -lpq > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > After a little bit of googling, I found that this can be solved > by -L while linking - but I am not specifically > linking the code. Rather, I am installing by doing the following - I don't think the lpq library comes (in the correct format) with the latest versions of PostgreSQL hence I had the same problem which I never resolved. You can get windows binaries from http://www.stickpeople.com/projects/python/win-psycopg/ though. HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
Markov Analysis Help
Hi Guys,
I've written a Markov analysis program and would like to get your
comments on the code As it stands now the final input comes out as a
tuple, then list, then tuple. Something like ('the', 'water') ['us']
('we', 'took')..etc...
I'm still learning so I don't know any advanced techniques or methods
that may have made this easier.
here's the code:
def makelist(f):#turn a document into a list
fin = open(f)
results = []
for line in fin:
line = line.replace('"', '')
line = line.strip().split()
for word in line:
results.append(word)
return results
def markov(f, preflen=2): #f is the file to analyze, preflen is prefix
length
convert_file = makelist(f)
mapdict = {}#dict where the prefixes will map to suffixes
start = 0
end = preflen #start/end set the slice size
for words in convert_file:
prefix = tuple(convert_file[start:end]) #tuple as mapdict
key
suffix = convert_file[start + 2 : end + 1] #word as suffix to
key
mapdict[prefix] = mapdict.get(prefix, []) + suffix #append
suffixes
start += 1
end += 1
return mapdict
def randsent(f, amt=10): #prints a random sentence
analyze = markov(f)
for i in range(amt):
rkey = random.choice(analyze.keys())
print rkey, analyze[rkey],
The book gave a hint saying to make the prefixes in the dict using:
def shift(prefix, word):
return prefix[1:] + (word, )
However I can't seem to wrap my head around incorporating that into the
code above, if you know a method or could point me in the right
direction (or think that I don't need to use it) please let me know.
Thanks for all your help,
Dave
--
http://mail.python.org/mailman/listinfo/python-list
Re: Markov Analysis Help
On 2008-05-17 06:01:01 -0600, [EMAIL PROTECTED] said: dave, few general comments to your code: - Instead of using a comment that explains the meaning of a function, add such things into docstrings. - Your names can be improved, instead of f you can use file_name or something like that, instead of convert_file you can use a name that denotes that the conversion is already done, etc. - You can use xrange instead of range and you can indent less, like 4 spaces. - This line may be slow, you may want to find simpler ways to do the same thing: rkey = random.choice(analyze.keys()) - I suggest you to add doctests to all your functions. Bye, bearophile bear, thanks for the suggestions. I use IDLE to write the code and when it's working I paste it over into a new window. I'll tabify before saving the pasted code. To add doctests would I need to use a certain filename for the tests to be run on? Can you have doctests on random functions? Thanks Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: namespaces and eval
On May 17, 12:20 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] writes:
> > On May 16, 2:47 pm, "[EMAIL PROTECTED]"
> > <[EMAIL PROTECTED]> wrote:
> >> On 16 mai, 23:23, [EMAIL PROTECTED] wrote:
>
> >> > Thanks for the responses. I'm well aware that the function can be
> >> > passed in the parameters, passing in the functino as an arg defeats
> >> > the purpose of what I'm going after.
>
> >> Why so ?
> >> > @ Arnaud - Nice. I'm not sure what the performance of mine vs. yours,
> >> > but a perfunctory glance looks like we're doing the close to the same
> >> > thing. Maybe one advanage to doing it wrap(x).foo() is that you
> >> > can pass in other parameters to foo.
>
> >> I may be wrong (if so please pardon my lack of intelligence and/or
> >> provide a couple use case), but it looks like you're trying to
> >> reinvent partial application.
>
> >> from functools import partial
> >> def foo(x, y):
> >> return x + y
>
> >> pfoo = partial(foo, 2)
> >> print pfoo(42)
>
> >> Don't know if this helps...
>
> > Ok, so that solves the issue of the aforementioned compose function.
> > We could do compose( partialfoo,) ) etc (although I might say I
> > prefer wrap(x).foo(23).foo(16 ..etc ) The original idea was to
> > provide wrapper around an object that lets you call abritrary
> > functions on that object with it as a parameter - i.e., as if it were
> > a method in a class. The partial function was only a component of the
> > code I posted earlier. Or am I missing something you're saying?
>
> Ok so you want to do
>
> wrap(x).foo(42).bar('spam')...
>
> What is the advantage over
>
> foo(x, 42)
> bar(x, 'spam')
> ...
>
> ?
>
> --
> Arnaud
*shrug*, just syntactic preference I guess. In jquery, for example,
you are working over sets of DOM elements and it's convenient to chain
those statements into a single line of x.foo().bar().biz() etc. IMO
it's a little cleaner to do that as an 'atomic' line, but it's not
really that different. Ideally the classes you are using would
support this without 'wrap' but I was just tinkering with a hack to do
it that way.
Thanks for the help
dave
--
http://mail.python.org/mailman/listinfo/python-list
Bring object 'out of' Class?
Hello,
I'm currently on the class section of my self-taught journey and have a
question about classes: is it possible to bring a object created
inside the class definitions outside the class so it can be accessed in
the interpreter?
For example, right now I'm working (within Allen Downey's Python
Programmer book) with creating a 'hand' of cards. I want to be able to
deal to 'x' amount of cards to 'x' amount of hands and then be able to
manipulate those hands afterwards. I'm not sure if even what I'm
asking is possible or if I'm getting ahead of myself.
As always, thanks for all your help. My learning is greatly enhanced
with everyone's input on this board. Please feel free to
comment/critique the code...
Here is the section of code that deals hands (but doesn't do anything
past that):
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '%s' % (handname.label), '\n', handname, '\n'
and here is the all of the code:
#!/usr/bin/env python
import random
class Card:
"""represents a playing card
attributes: rank, suit"""
def __init__(self, suit=0, rank=3):
self.suit = suit
self.rank = rank
suit_names = ["Clubs", "Diamonds", "Hearts", "Spades"]
rank_names = [None, "Ace", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King"]
def __str__(self):
#prints card in format: Rank 'of' Suit#
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])
def __cmp__(self, other):
#evaluates which card is ranked higher by suit/rank
#arbitrary definition. depends on the card game
card1 = self.suit, self.rank
card2 = other.suit, other.rank
return cmp(card1, card2)
class Deck:
"""represents a deck of cards. 52 card, 4 suits, 13 cards/suit"""
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
return '\n'.join(res)
def pop_card(self):
'''removes a card and returns it to another object'''
return self.cards.pop()
def add_cards(self, card):
#adds a card to an object
return self.cards.append(card)
def shuffle(self):
'''must import random, shuffles the deck'''
random.shuffle(self.cards)
def sort_deck(self):
self.cards.sort()
def deal(self, hand, num):
'''moves cards from one object to another'''
for i in range(num):
hand.add_cards(self.pop_card())
def deal_cards(self, num_of_hands, num):
'''deals x amount of cards(num) to each hand'''
for i in range(num_of_hands):
handname = Hand('hand%d' % i)
self.deal(handname, num)
print '%s' % (handname.label), '\n', handname, '\n'
class Hand(Deck):
"""child class of Deck. Represents a hand of cards"""
def __init__(self, label=" "):
self.cards = []
self.label = label
--
http://mail.python.org/mailman/listinfo/python-list
Re: Bring object 'out of' Class?
Then you can write: hands = deck.deal_cards(4, 5) # On fait une belotte? And I don't see the need of defining 'Hand' inside 'Deck'. HTH Thanks for the input. I believe using 'class Hand(Deck):' is to illustrate (in the book) inheritance and how it can be used. By using 'Hand(Deck)' I can then use the methods (pop_card, add_cards, etc..) defined in the 'Deck' class. -- http://mail.python.org/mailman/listinfo/python-list
Most effective coding.. IDE question.
Hello everyone, I'm a beginning self-taught python student. Currently, I work out my code within IDLE then when I have a version that I like, or that's working, I move it over to a new window and save it. I've been playing w/ Komodo IDE lately, and while it's nice, what I don't like is the "one line at a time" (produced by hitting up-arrow) in the shell. In IDLE, ctrl-p can reproduce a whole function or class - opposed to only the last line in Komodo. Is my IDLE method common? Or am I simply creating more of a headache for myself? What do you recommend? I'm not that advanced and don't need anything fancy. I'm on OS X. Thanks! Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: PyPy questions
On 1 Jul, 04:09, Allen <[EMAIL PROTECTED]> wrote: > I read the website of some information about PyPy, and how a translator > translates the RPython code to C/CLI/Java/etc to be compiled to a native > executable or something like that. Would it be possible, in PyPy, to > write such an extension that could easily be compiled to native code > from Python code? Is this functionality planned in a future release of > it? Also, how is the source distributed (If I opt to use it I will end > up compiling it on a system without an initial python install (a scratch > linux system)), so does the source include the generated C code? > > B. Vanderburg II Were you thinking of something like this? http://www.enthought.com/~ischnell/compdec.html -Dave -- http://mail.python.org/mailman/listinfo/python-list
imap4_SSL from behind a proxy server
First to admit I'm a newbie at Python, IMAP, or SSL. And it's been a long time since I've posted anything to a Usenet group. But I've spent countless hours spinning my wheels on this one, so I thought I'd ask for help. I'm trying write some Python code to connect to Gmail from work, where I need to direct all non-HTTP traffic through a proxy server. Can anyone provide syntax which would redirect the imap4_SSL method through a proxy server:port? I suspect there are some environment variables which, when set, will do this very easily and elegantly. I also suspect there is a really complicated way to 'wrap' the imap classes so as to force requests to go through a proxy which, as a newbie, I am trying to avoid. FYI, I'm currently running Python 2.5.2. via IDLE on Windows XP. But when this project is done, I will move it to Linux. Thanks for any help. Dave fkaprince, at Gmail, dot-com -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimals not equalling themselves (e.g. 0.2 = 0.2000000001)
On 3 Aug, 15:02, CNiall <[EMAIL PROTECTED]> wrote: > However, with some, but not all, decimals, they do not seem to 'equal > themselves'. Back in my days studying electrical engineering I was pointed to this reference about floating point arithmetic - http://citeseer.ist.psu.edu/goldberg91what.html HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list
newb loop problem
Hey there, having a bit of problem iterating through lists before i go on any further, here is a snip of the script. -- d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 c5 d5 e5" inLst = d.split() hitLst = [] hitNum = 0 stopCnt = 6 + hitNum for i in range(hitNum,len(inLst), 1): if i == stopCnt: break hitLst.append(inLst[i]) print hitLst -- $ python helper.py ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] This works fine for my purposes, what I need is an outer loop that goes through the original list again and appends my next request. ie. hitNum = 5 which will return: ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] and append it to the previous one. ie: ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] not really sure how to do this right now though, been trying several methods with no good results. btw, just creating lagged values (sort of shift registers) on the incoming signal Many thanks, Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: newb loop problem
On Aug 13, 12:35 am, Larry Bates <[EMAIL PROTECTED]> wrote: > Dave wrote: > > Hey there, having a bit of problem iterating through lists before i go > > on any further, here is > > a snip of the script. > > -- > > d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 > > c5 d5 e5" > > inLst = d.split() > > hitLst = [] > > > hitNum = 0 > > stopCnt = 6 + hitNum > > > for i in range(hitNum,len(inLst), 1): > >if i == stopCnt: break > >hitLst.append(inLst[i]) > > > print hitLst > > -- > > $ python helper.py > > ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] > > > This works fine for my purposes, what I need is an outer loop that > > goes through the original list again and appends my next request. > > > ie. > > > hitNum = 5 > > > which will return: > > > ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] > > > and append it to the previous one. > > > ie: > > > ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] > > ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] > > > not really sure how to do this right now though, been trying several > > methods with no good results. > > > btw, just creating lagged values (sort of shift registers) on the > > incoming signal > > > Many thanks, > > > Dave > > Dave, > > You are going to need to supply us with more info to help. > > 1) Are you always going to want to get 6 elements from the list > 2) Are you always going to want to step by 5 elements as your offset each time > through the outer loop? > 3) Is your requirement just to split inLst into equal length lists and append > them together into a list? > > Depending on your answers this might be quite easy. > > -Larry Hi Larry, well to answer your questions. 1) Are you always going to want to get 6 elements from the list yes for this example, but this will change depending on the length of the sig. hitNum will be changing depending on what element I need to lag ie: if hitNum = 1 ['b1', 'c1', 'd1', 'e1', 'a2', 'b2'] so I will be lagging the b elements. 2) Are you always going to want to step by 5 elements as your offset each time through the outer loop? I think I just answered this 3) Is your requirement just to split inLst into equal length lists and append them together into a list? yes Thanks for all your help, Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: newb loop problem
arrrggg, now I feel really dumb.. hitNum = 0 stopCnt = 6 + hitNum offSet = 5 for i in range(0,10,1): for x in range(hitNum,len(inLst), 1): print hitNum, stopCnt if x == stopCnt: break hitLst.append(inLst[x]) hitNum +=offSet stopCnt+=offSet print hitLst Beers, Dave On Aug 13, 12:58 am, Dave <[EMAIL PROTECTED]> wrote: > On Aug 13, 12:35 am, Larry Bates <[EMAIL PROTECTED]> wrote: > > > > > Dave wrote: > > > Hey there, having a bit of problem iterating through lists before i go > > > on any further, here is > > > a snip of the script. > > > -- > > > d = "a1 b1 c1 d1 e1 a2 b2 c2 d2 e2 a3 b3 c3 d3 e3 a4 b4 c4 d4 e4 a5 b5 > > > c5 d5 e5" > > > inLst = d.split() > > > hitLst = [] > > > > hitNum = 0 > > > stopCnt = 6 + hitNum > > > > for i in range(hitNum,len(inLst), 1): > > >if i == stopCnt: break > > >hitLst.append(inLst[i]) > > > > print hitLst > > > -- > > > $ python helper.py > > > ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] > > > > This works fine for my purposes, what I need is an outer loop that > > > goes through the original list again and appends my next request. > > > > ie. > > > > hitNum = 5 > > > > which will return: > > > > ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] > > > > and append it to the previous one. > > > > ie: > > > > ['a1', 'b1', 'c1', 'd1', 'e1', 'a2'] > > > ['a2', 'b2', 'c2', 'd2', 'e2', 'a3'] > > > > not really sure how to do this right now though, been trying several > > > methods with no good results. > > > > btw, just creating lagged values (sort of shift registers) on the > > > incoming signal > > > > Many thanks, > > > > Dave > > > Dave, > > > You are going to need to supply us with more info to help. > > > 1) Are you always going to want to get 6 elements from the list > > 2) Are you always going to want to step by 5 elements as your offset each > > time > > through the outer loop? > > 3) Is your requirement just to split inLst into equal length lists and > > append > > them together into a list? > > > Depending on your answers this might be quite easy. > > > -Larry > > Hi Larry, well to answer your questions. > > 1) Are you always going to want to get 6 elements from the list > > yes for this example, but this will change depending on the length of > the sig. > hitNum will be changing depending on what element I need to lag ie: > > if hitNum = 1 > > ['b1', 'c1', 'd1', 'e1', 'a2', 'b2'] > > so I will be lagging the b elements. > > 2) Are you always going to want to step by 5 elements as your offset > each time > through the outer loop? > > I think I just answered this > > 3) Is your requirement just to split inLst into equal length lists and > append > them together into a list? > > yes > > Thanks for all your help, > > Dave -- http://mail.python.org/mailman/listinfo/python-list
dict invert - learning question
Hello,
here is a piece of code I wrote to check the frequency of values and
switch them around to keys in a new dictionary. Just to measure how
many times a certain key occurs:
def invert(d):
inv = {}
for key in d:
val = d[key]
if val not in inv:
inv.setdefault(val, [key])
else:
inv[val].append(key)
return inv
Using the methods above (I'm just a beginner) could I have written it
more concisely? Any criticism/critique in the code would be greatly
appreciated.
Many Thanks,
dave
--
http://mail.python.org/mailman/listinfo/python-list
Re: dict invert - learning question
thanks Duncan and Arnaud.
I'm learning Python from the "How to Think Like a Python Programmer"
book by Allen Downey. My first try used the "inv[val] = [key]" and
then the next problem was to incorporate the "D.setdefault(...)" method.
Thank you for your help. I'm always amazed how kind people are in this group.
On 2008-05-03 14:57:29 -0600, Arnaud Delobelle <[EMAIL PROTECTED]> said:
dave <[EMAIL PROTECTED]> writes:
Hello,
here is a piece of code I wrote to check the frequency of values and
switch them around to keys in a new dictionary. Just to measure how
many times a certain key occurs:
def invert(d):
inv = {}
for key in d:
val = d[key]
if val not in inv:
inv.setdefault(val, [key])
You can simply write:
inv[val] = [key]
else:
inv[val].append(key)
return inv
Using the methods above (I'm just a beginner) could I have written it
more concisely? Any criticism/critique in the code would be greatly
appreciated.
Apart from the unnecessary use of setdefault, it looks good to me.
* You could change if 'val not in inv:' to 'if val in inv:' (and swap
the if and else clauses of course) in order to have a positive
condition rather than a negative one
* If you want to use setdefault, you can replace the if .. else
construct by:
inv.setdefault(val, []).append(key)
* You can also iterate over keys and values using the items() or
iteritems() method of dictionaries:
def invert(d):
inv = {}
for key, val in d.iteritems():
inv.setdefault(val, []).append(key)
return inv
--
http://mail.python.org/mailman/listinfo/python-list
word shifts
Hello,
I made a function that takes a word list (one word per line, text file)
and searches for all the words in the list that are 'shifts' of
eachother. 'abc' shifted 1 is 'bcd'
Please take a look and tell me if this is a viable solution.
def shift(word, amt):
ans = ''
for letter in word:
ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a'))
return ans
def fileshift(x):
fin = open(x)
d = {}
for line in fin:
d[line.strip()] = [1]
for i in range(1, 26):
ite = shift(line.strip(), i)
if ite in d:
print ite
Any tips/suggestions/critiques greatly appreciated.. I'm trying to
teach myself Python (and still beginning) and would love any helpful
info.
thanks!
--
http://mail.python.org/mailman/listinfo/python-list
Re: word shifts
On 2008-05-04 01:10:40 -0600, Arnaud Delobelle <[EMAIL PROTECTED]> said:
dave <[EMAIL PROTECTED]> writes:
Hello,
I made a function that takes a word list (one word per line, text
file) and searches for all the words in the list that are 'shifts' of
eachother. 'abc' shifted 1 is 'bcd'
Please take a look and tell me if this is a viable solution.
def shift(word, amt):
ans = ''
for letter in word:
ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a'))
return ans
In Python, if you want to build a string from lots of parts you can
use ''.join(parts). I think it is considered more efficient.
what would be the best way to write a "ans = ans + chr" into a
''.join(parts) ??
--
http://mail.python.org/mailman/listinfo/python-list
anagram finder / dict mapping question
Hi All,
I wrote a program that takes a string sequence and finds all the words
inside a text file (one word per line) and prints them:
def anagfind(letters): #find anagrams of these letters
fin = open('text.txt') #one word per line file
wordbox = [] #this is where the words will go
for line in fin:
word = line.strip()
count = 0
for char in letters:
if char not in word:
break
else:
count += 1
if count == len(word):
wordbox.append(word)
return wordbox
Now I'd like to modify the code to naturally find all anagrams inside a
wordlist. What would be the best way to do this? Using Hints? Is it
possible to iterate over dict keys? How can I make a dict that maps
from a set of letters to a list of words that are spelled from those
letters? Wouldn't I need to make the set of letters a key in a dict?
As always - Thanks for helping someone trying to learn...
Dave
--
http://mail.python.org/mailman/listinfo/python-list
