Python Count Lines and words

Posted by on Apr 18, 2012 in python | No Comments

Python count lines in file:

filename = raw_input('file? ')
file = open(filename)

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

print '%r has %r lines' % (filename, lines)

Python count words in file:

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

Python import modules

Posted by on Dec 30, 2011 in python | No Comments

Simple workaround to setting the environment variable, so that you can import custom modules saved at the specified path.

import os,sys
sys.path.append('/path/to/modules/')

Else to set the environment variable on the Mac by adding:

export PYTHONPATH=/path/to/modules/

to the .bashrc file

Python file renaming

Posted by on Dec 10, 2011 in python | No Comments

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.

# 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+=1

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

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.


# 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)




Python, word count

Posted by on Oct 14, 2011 in code, python | No Comments

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.

# 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


Python tip, list contents of directory

Posted by on Aug 3, 2011 in how to, python | No Comments

Python: list contents of a directory, remove an extension from the file names.

import os
dirList=os.listdir('path')
for fname in dirList:
    print fname.replace('.ext','')

create a grid of cubes

Posted by on Sep 29, 2010 in code, how to, Maya, MEL, python | No Comments

Grid of cubes in Maya.

# create a grid of cubes, their bottom plane set to zero y, and the center point at zero y.
x = -20
count = 0
cubes = []
while x <= 20:
	z = -20
	while z <= 20:
		cube = mc.polyCube( name = ('polyCube_' + str(count) + '_' + str(x) + str(z)) )
		count +=1
		cubeName=cube[0]
		cubes.append(cubeName)
		mc.setAttr((cubeName + '.translateY'), .5);
		mc.makeIdentity(apply=True, t =True, r=True, s=True, n= 0)
		mc.ResetTransformations()
		mc.move(x, 0, z)
		z += 1
	x +=1

Block of cubes

import maya.cmds as mc
# create a block grid of cubes
# change the mult number below to change the amount of cubes created.
mult =  3;
count = 0
cubes = []
y = mult - mult
while y <= mult *2:
    x = mult * -1
    while x <= mult:
	    z = mult * -1
	    while z <= mult:
		    cube = mc.polyCube( name = ('cube_' + str(count) ) )
		    count +=1
		    cubeName=cube[0]
		    cubes.append(cubeName)
		    mc.move(x, y, z)
		    z += 1
	    x +=1
    y +=1

Make a 3d cube grid, based on a selected object’s bounding box.

//MEL
proc makeCubeGrid(int $cubeGridDiv)
{
    string $cube[];
    string $cubes[] = {};
    string $sel[] = `ls -long -sl`;
    float $bBox[] = `polyEvaluate -b -ae $sel[0]`;

    float $w = ($bBox[1] - $bBox[0]) / $cubeGridDiv;
    float $h = ($bBox[3] - $bBox[2]) / $cubeGridDiv;
    float $d = ($bBox[5] - $bBox[4]) / $cubeGridDiv;

    float $p[3];
    for($i=0;$i<$cubeGridDiv;$i++)
    {
        $p[0] = $bBox[0] + (($bBox[1] - $bBox[0]) / $cubeGridDiv) * $i;
        for($k=0;$k<$cubeGridDiv;$k++)
        {
            $p[1] = $bBox[2] + (($bBox[3] - $bBox[2]) / $cubeGridDiv) * $k;
            for($n=0;$n<$cubeGridDiv;$n++)
            {
                $p[2] = $bBox[4] + (($bBox[5] - $bBox[4]) / $cubeGridDiv) * $n;
                $cube = `polyCube -w $w -h $h -d $d -sx 1 -sy 1 -sz 1 -ax 0 0 0 -ch 0`;
                move ($p[0] + $w / 2) ($p[1] + $h / 2) ($p[2] + $d / 2) $cube[0];
                makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 $cube[0];
                $cubes[`size $cubes`] = $cube[0];
            };
        };
    };
    string $group = `group -em -n "cubes"`;
    parent $cubes $group;
};

makeCubeGrid(10);

Create a Graphic EQ using SoundKeys and Maya

Posted by on Sep 26, 2010 in animation, code, Maya, MEL, python | 10 Comments

You can create this graphic equalizer with Trapcode Soundkeys and Maya. Use my Python script, below, to automatically import keyframe data and create the eq.

Trapcode Soundkeys, an Adobe After Effects plugin, breaks audio into into about 27 frequency blocks, “ranges”, and allows you to drive animation, set keyframes, or export keyframes. To export keys, copy the keyframes from the After Effects timeline, then paste into a text editor to create your data.txt files. Each frequency range should have it’s own text file, named sequentially. Use a code editor like BB Edit or Text Wrangler, as these apps will save your .txt files with UNIX line returns, which are necessary to make my Python script work properly.

Place all the data files in a directory, by themselves, and use the Python script below to automatically build the EQ in Maya.

## make a graphic equalizer, based on keyframe data from After Effects and Sound Keys.
import os
import maya.cmds as mc
## add path to keyframe data files - just the source directory that contains them.
rootdir='/path/to/data/folder'
theAttribute = 'data'
count = 0
theCubes = []
for subdir, dirs, files in os.walk(rootdir):
	dataFiles = [each for each in files if each.endswith('.txt')]
	for thisFile in dataFiles:
		## create a cube for each data file, and distibute them across the  X axis
		mc.polyCube()
		cube = mc.ls(sl = True)
		cubeName=cube[0]
		theCubes.append(cubeName)
		mc.setAttr((cubeName + '.translateY'), .5);
		mc.makeIdentity(apply=True, t =True, r=True, s=True, n= 0)
		mc.ResetTransformations()
		mc.move( count -(len(dataFiles)/2), 0, 0)
		count +=1
count = 0
for subdir, dirs, files in os.walk(rootdir):
	dataFiles = [each for each in files if each.endswith('.txt')]
	for thisFile, o in zip(dataFiles, theCubes):
		## prepare each cube for animation by ading an attibute to accept the keys, and creating an expression
		theName = theCubes[count]
		mc.addAttr( theName, shortName='data', longName='data', defaultValue=1.0)
		mc.setAttr ( (theName + '.data'), e=True, keyable=True)
		mc.expression(o=theName, s = (theName + '.scaleY =' +  theName + '.data / 4'),  ae = True, uc = all)
		## make shader for each cube
		myBlinn = mc.shadingNode('blinn', asShader=True, name = ("myBlinn" + str(count)))
		myShader = mc.sets(renderable=True, noSurfaceShader=True, empty=True, name = ('myBlinn' + str(count) + 'SG'))
		mc.connectAttr( (myBlinn + ".outColor"), (myShader + ".surfaceShader"), f=True)
		mc.setAttr((myBlinn + ".color"), 0.1, 0.1, 0.1, type ='double3' )
		mySetRange =  mc.shadingNode('setRange', asUtility=True)
		mySetRange2 = mc.shadingNode('setRange', asUtility=True)
		mc.setAttr((mySetRange + ".minX"),230)
		mc.setAttr((mySetRange + ".maxX") ,240)
		mc.setAttr((mySetRange + ".oldMaxX") ,25)
		mc.setAttr((mySetRange2 + ".maxX") ,3)
		mc.setAttr((mySetRange2 + ".minX") ,.1)
		mc.setAttr((mySetRange2 + ".oldMaxX") ,25)
		myRamp = mc.shadingNode('ramp', asTexture=True)
		my2dPlace = mc.shadingNode('place2dTexture', asUtility=True)
		mc.connectAttr((my2dPlace + ".outUV"), (myRamp + ".uv"))
		mc.connectAttr((my2dPlace + ".outUvFilterSize"), (myRamp + ".uvFilterSize"))
		mc.setAttr((myRamp + ".colorEntryList[2].color"), 0, 0, 0 , type = 'double3')
		mc.removeMultiInstance((myRamp + ".colorEntryList[0]"), b=True )
		mc.removeMultiInstance(myRamp + ".colorEntryList[1]", b=True )
		mc.connectAttr( (theName + ".scaleY"), (mySetRange + ".valueX"), f=True)
		mc.connectAttr( (theName+ ".scaleY"), (mySetRange2 + ".valueX"), f=True)
		mc.connectAttr( (theName + ".scaleY"), (mySetRange2 + ".valueY"), f=True)
		mc.connectAttr( (theName + ".scaleY"), (mySetRange2 + ".valueZ"), f=True)
		myhsvToRgb = mc.createNode('hsvToRgb', ss=True)
		mc.setAttr((myhsvToRgb+".inHsv"), .75, .75, .75)
		mc.connectAttr( (mySetRange + ".outValueX"), (myhsvToRgb + ".inHsvR"), f=True )
		mc.connectAttr( (myRamp  + ".outColor"), (myBlinn + ".incandescence"), f=True )
		mc.connectAttr( (myhsvToRgb + ".outRgb"), (myRamp+ ".colorEntryList[2].color"), f=True )
		mc.connectAttr( (mySetRange2 + ".outValue"), (myRamp + ".colorGain"), f=True )
		mc.select(theName)
		mc.sets( e=True, forceElement= myShader)
		count +=1
		## read keyframe data and set keyframes
		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))
## the code below will set the playback range to equal the amount of the keyframe data in the files
fileData = open(rootdir + '/' + dataFiles[0])
lines= fileData.readlines()
fileData.close()
myLines = lines[10:-4]
countLines = len(myLines)
mc.playbackOptions( minTime='0sec', maxTime=countLines)

Sample keyframe data, exported from After Effects.

Python import/export Maya keyframes script

Posted by on Sep 19, 2010 in code, MEL, python | No Comments

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

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()

Import Maya Keys
This will import keys to nodes which are named identically to the nodes that were selected when the keys were exported.

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()

Python – round, limit decimal places

Posted by on Sep 16, 2010 in code, python | No Comments
pi = 3.14159265

print(pi)
# Result: 3.14159265 #

print("%.2f" % pi)
# Result: 3.14 #

round(pi,3)
# Result: 3.142 # 

print("%.1f" % round(pi,0))
# Result: 3.0 # 
Load More