halamas 0 Newbie Poster

hello,
I'm a computer sciense student has to learn python by myself, I have a task to accomplish, that is a litlle bit ambiguous for me!
I have to read fro a text file and make a word_counter then I have to search for a word and replace it with another one using the getopt parser. The thing that I'm having troubles with is that when I have to parse the two arrguments to the parser, here is what I have written wich is true but need completetion in the last issue I mentioned:

#!/usr/bin/python
def write(file_name):
        f=open(file_name,'a')
        f.writelines('\nhello word')
        f.close()
def empty(file_name):
        f=open(file_name,'r')
        data = f.readlines()
        f.close()
        del data[0:]
        f=open('a.txt','w')
        f.writelines(data)
        f.close()

def counter(file_name):
        lines = 0
        words = 0
        blanklines = 0
        f = open(file_name, 'r')
        for line in f:
                lines+=1
                if line.startswith('\n'):
                        blanklines+=1
                else:
                        temp=line.split(None)
                        words+=len(temp)
        f.close()
        print "no. of words is %d" % words
        print "no. of blanklines is %d" % blanklines


def usage():
    print"this program takes a text file (-i<file_name) and counts the word and
 characters in it(-c):returns the value of the counters, you can maka a file em
pty by using -m.. write (hello word)to your file in a new line using -w... in a
ll cases you should start by -i<file name> "
        
import sys
import getopt
count=False

opts,extraparams= getopt.getopt(sys.argv[1:],"hi:cmwr:e:n:",['help'])
if (len(extraparams)!=0):print('Error :'),sys.exit(1)
for o,p in opts:
    if o in ['--help','-h']:
        usage()
        sys.exit(1)
    elif o in ['-i']:
        file_name=p
    elif o in ['-c']:
        count=True
        counter(file_name)
    elif o in ['-m']:
        empty(file_name)
    elif o in ['-w']:
         write(file_name)

the -r shoud be followed by -e<old_word>, -n<new_word>


if anyone can help..thanks in advance :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.