Tagged: python

Python Count Lines and words

Python count lines in file:

[py collapse=”False”]
filename = raw_input(‘file? ‘)
file = open(filename)

lines = 0
for line in file:
lines += 1

print ‘%r has %r lines’ % (filename, lines)
[/py]

Python count words in file:

[py collapse=”False”]
filename = "words.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, ‘r’) as f:
for line in f:
words = line.split()

num_lines += 1
num_words += len(words)
num_chars += len(line)

print num_words
[/py]

Python file renaming

A renaming script that I use to rename photos, rendered animation, or video frames. Warning, this script will rename your files! There is no undo. Use with care. Constructive comments about Python usage very welcome.

Will work on Unix-like operating systems, not sure about Windows.

[py]
# Python renamer script: creates a function called pyrename(). pyrename() will rename all files in a given folder.
# Usage: Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().
# Warning, this script will rename your files. There is no undo. Use with care.
def pyrename():
‘Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().’
import os

#function to ignore the hidden . files in a directory. Note the use of the ‘yield’ keyword
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith(‘.’):
yield f

path = raw_input(‘path to folder?: ‘)
#get the files from the folder and put the filenames in a list called files
theFiles = listdir_nohidden(path)
files = []
for f in theFiles:
files.append(f)

#user supplied values
print ‘Want to replace a character or string in your file names?’
want_to_replace = raw_input(‘Type y or n. Or to completely rename type w: ‘)
if want_to_replace == ‘y’:
replace = raw_input(‘Type the character or string that you want to replace (FYI can be a space!): ‘)
replace_with = raw_input(‘Type the character or string that you want to replace with: ‘)
elif want_to_replace == ‘w’:
replace = ”
replace_with = raw_input(‘Type new name: ‘)
else:
replace = ”
replace_with = ”

if want_to_replace != ‘w’:
want_numbers = raw_input(‘Want your files numbered? type y or n: ‘)
if want_numbers == ‘y’:
zeros = raw_input(‘Type the amount of padding zeros you need (using a single integer, like 4): ‘)
else:
zeros = 0

if want_to_replace == ‘w’:
zeros = raw_input(‘Type the amount of padding zeros you need (using a single integer, like "4"): ‘)

ext = raw_input(‘Please type the three letter extension you want to use ex: jpg (NOT the .): ‘)

#remove extension, put the filenames in a list called names
names = []
for f in files:
if f[-4] == ‘.’:
names.append(f.replace(f[-4:], ”))
else:
names.append(f)

#add new names, add user supplied extension, put the filenames in a list called namesPlusEx
namesPlusEx = []
count = 0
for f in names:
if want_to_replace == ‘w’:
namesPlusEx.append(f.replace(f, replace_with)+ ((‘.%.’)+zeros+(‘d’))% count +’.’+ ext)
elif want_to_replace != ‘w’ and want_numbers == ‘y’:
namesPlusEx.append(f.replace(replace, replace_with)+ ((‘.%.’)+zeros+(‘d’))% count +’.’+ ext)
else:
namesPlusEx.append(f.replace(replace, replace_with)+’.’+ ext)
count += 1

#rename the actual files
c=0
for f in files:
os.rename(path+’/’+f, path+’/’+namesPlusEx[c])
c+=1

print ‘You have re-named %d files’ % len(files)

[/py]

rename.py

The following script will remove the first four characters of all files in a specified folder. You may alter the script to remove other characters by altering this line: names.append(f.replace(f[0:4], ”)) change the 0:4 to another bit as defined by python slice notation.

[py]

# Python renamer script: creates a function called pyrename(). pyrename() will rename all files in a given folder.
# Usage: Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().
# Warning, this script will rename your files. There is no undo. Use with care.
def pyrename():
‘Put all the files you want to rename in an isolated folder. The function can be called by typing pyrename().’
import os

#function to ignore the hidden . files in a directory. Note the use of the ‘yield’ keyword
def listdir_nohidden(path):
for f in os.listdir(path):
if not f.startswith(‘.’):
yield f

path = raw_input(‘path to folder?: ‘)
#get the files from the folder and put the filenames in a list called files
theFiles = listdir_nohidden(path)
files = []
for f in theFiles:
files.append(f)

#remove extension, put the filenames in a list called names
names = []
for f in files:
names.append(f.replace(f[0:4], ”))

#rename the actual files
i=0
for f in files:
os.rename(path+’/’+f, path+’/’+names[i])
i+=1

print ‘You have re-named %d files’ % len(files)

[/py]

Python, word count

A simple program that will count the words and sentences in a text file. Sightly modified version of the code I found on daniweb.com.

[py]
# count lines, sentences, and words of a text file

# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0

# write the trs file
fname = "/path/filename.txt"

# read the file back in
textf = open(fname, "r")

# reads one line at a time
for line in textf:
#print line, # test
lines += 1

if line.startswith(‘\n’):
blanklines += 1
else:
# assume that each sentence ends with . or ! or ?
# so simply count these characters
sentences += line.count(‘.’) + line.count(‘!’) + line.count(‘?’)

# create a list of words
# use None to split at any whitespace regardless of length
# so for instance double space counts as one space
tempwords = line.split(None)
#print tempwords # test

# word total count
words += len(tempwords)

textf.close()

print ‘-‘ * 50
print "Lines : ", lines
print "Blank lines: ", blanklines
print "Sentences : ", sentences
print "Words : ", words

[/py]

Python import/export Maya keyframes script

These are fairly rudimentary python scripts, to export keys from Maya and import them back into Maya. Creates a key at every frame. May be interesting to people learning Python.

Export Maya Keys
[py]
import maya.cmds as mc
# Select all nodes with keys to export
# Customize the path below so that it points to, or creates, the file where you want to store the keyframe data
myFileObject=open(‘/mydataDir/data.txt’, ‘w’)
obs = mc.ls(sl=True)
theData = []
minTime = mc.playbackOptions(query=True, minTime=True)
maxTime = mc.playbackOptions(query=True, maxTime=True)
attributes = [‘translateX’, ‘translateY’, ‘translateZ’, ‘rotateX’, ‘rotateY’, ‘rotateZ’, ‘scaleX’, ‘scaleY’, ‘scaleZ’, ‘visibility’]
for time in range(minTime -1, maxTime +1):
mc.currentTime(time)
count = 0
for selection in obs:
name = obs[count]
count +=1
for theAttribute in attributes:
myAtF = mc.getAttr(selection + ‘.’ + theAttribute)
myAt = str(myAtF)
myTime = str(time)
theData.append(myAt + ‘ ‘ + myTime + ‘ ‘ + theAttribute + ‘ ‘ + name + ‘ \n’)
for lines in theData:
myFileObject.writelines(lines)
myFileObject.close()
[/py]

Import Maya Keys
This will import keys to nodes which are named identically to the nodes that were selected when the keys were exported.
[py]
import maya.cmds as mc
# Customize the path below so that it points to the file where you have exported the keyframe data
myFileObject=open(‘/mydataDir/data.txt’, ‘r’)
theLines = myFileObject.readlines()
count = 0
for line in theLines:
theLine = theLines[count]
theSplit = str.split(theLine)
theValue = theSplit[0]
theFrame = theSplit[1]
theAttribute = theSplit[2]
theName = theSplit[3]
mc.setKeyframe( theName, v=float(theValue), at=theAttribute, t =float(theFrame))
count +=1
myFileObject.close()
[/py]

Importing keyframe data to Maya

Use this python script to import keys to a single channel of each node in a group of selected objects. This setup, below, will import properly formatted keys to the .translateY attribute of selected objects.

This script will apply unique keys to each selected node if there is a corresponding number of data files in the source directory.

[py]import os
import maya.cmds as mc
## add path to keyframe data files – just the source directory that contains them.
rootdir=’/path/to/keys’
## "ty", in line 13, refers to the Maya attribute channel of the selected objects. Modify this attribute as necessary.
objs= mc.ls(sl=True)
for subdir, dirs, files in os.walk(rootdir):
for thisFile, o in zip(files, objs):
file = open((os.path.join(rootdir, thisFile)), ‘r’)
lines = file.readlines()
file.close()
for i in range(len(lines)):
mc.setKeyframe(o, at=’ty’, v=float(lines[i]), t=i, itt=’linear’, ott=’linear’)
[/py]

See a sample of properly formatted keyframe data :
http://oliverwolfson.com/scripts/keyFrameData.txt

Also see http://oliverwolfson.com/extracting-raw-key-frame-data/

NEW! The script below will do the same as the script above, import After Effects Sound Keys keyframes, from .txt files, to Maya, but it will also take care of the formatting, so there is no need to run a shell script on your After Effects keyframes before importing.

This script will apply unique keys to each selected node if there is a corresponding number of data files in the source directory.

[py]##AE Import
import os
import maya.cmds as mc
## add path to keyframe data files – just the source directory that contains them.
rootdir=’/Volumes/500GB/Work/Code/python/AEkeysImport/soundkeys’
## below is the attribute that you want to keyframe
theAttribute = ‘translateY’
count = 0
objs= mc.ls(sl=True)
for subdir, dirs, files in os.walk(rootdir):
dataFiles = [each for each in files if each.endswith(‘.txt’)]
for thisFile, o in zip(dataFiles, objs):
theName = objs[count]
count +=1
dataFile = open((os.path.join(rootdir, thisFile)), ‘r’)
lines = dataFile.readlines()
dataFile.close()
mylines = lines[10:-4]
for eachLine in mylines:
data = eachLine.split(‘\t’)
theFrame = data[1]
theValue = data[2]
mc.setKeyframe( o, v=float(theValue), at=theAttribute, t =float(theFrame))
[/py]

Note: When pasting the keys from After Effects, be sure to use a code text editor like BB Edit or Text Wrangler. These apps will save your .txt files with UNIX line returns which is necessary to make this script work properly.

Technically the line breaks are invisible, but using the ‘tr’ command, in a UNIX shell, you could display them as any character you like, eg:

[shell]
cat /path/some/file.txt | tr ‘\n’ ‘U’
[/shell]

In the above example, if the input file uses UNIX style line returns, \n ,each line will have a U at the end.