Although I've been coding in PHP and ASP and _javascript_ for a couple of years now, I'm relatively new to Python. For learning exercises, I'm writing small Python programs that do limited things, but hopefully do them well.
The following program takes a text file, reads through it, and any word longer than four characters will have the internal letters scrambled, but the first and last letters of the word will remain unchanged. Here's what happened when I ran the program on a file called example.txt.
Before:
This is a sample of text that has been scrambled, before and after.
After:
Tihs is a sapmle of txet taht has been sblrmcead, broefe and aetfr.
The code follows, so any comments and/or suggestions as to what I did right or wrong, or what could be done better will be appreciated.
thanks,
William
#!/usr/bin/env python
#filename: wScramble.py
#filelocation: /home/william/programming/code/python
#filedate: 12/25/2005
import sys
import random
def fileScramble(fileName):
newFile = file('scrambled.txt', 'w')
newRow = ''
for line in fileName:
newRow = ''
tempList = line.split(' ')
for word in tempList:
newRow = newRow + ' ' + wordScramble(word)
newRow = newRow + '\n'
newFile.write(newRow)
newFile.close()
def wordScramble(word):
punctuation = ['.', ',', ':', ';', '(', ')']
if len(word) < 4:
return word
elif len(word) == 4 and word[-1] in punctuation or word[0] in punctuation:
return word
elif len(word) == 4:
word = word[0] + word[2] + word[1] + word[3]
return word
else:
(fCut, fLetter) = getLetter(word, 0, 'forward')
(lCut, lLetter) = getLetter(word, -1, 'back')
tempWord = list(word)
del tempWord[:fCut + 1]
del tempWord[lCut:]
random.shuffle(tempWord)
middleString = "".join(tempWord)
scrambledWord = fLetter + middleString + lLetter
return scrambledWord
def getLetter(string, number, direction):
if direction == 'forward':
increment = 1
else:
increment = -1
if string[number].isalpha() == True:
if direction == 'forward':
return (number, string[:number + 1])
else:
return (number, string[number:])
elif string[number].isalpha() == False:
return getLetter(string, number + increment, direction)
if __name__ == "__main__":
try:
if sys.argv[1].isspace() == True:
print "No file was given to the program to process.\n<----------> Program quitting <---------->\n"
else:
try:
f = open(sys.argv[1])
fileScramble(f)
f.close()
except IOError:
print "That file does not exist, or you do not have permission to access it.\n<----------> Program quitting <---------->\n"
except IndexError:
print "No file was given to the program to process.\n<----------> Program quitting <---------->\n"
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor