Unique words in a file sorted alphabetically

 # Unique words in a file


fp = None


try:

fp = open("fileipt.txt","r")

except IOError as e:

print("File opening error : ", e)

except:

print("unknown error")


else:

fdata = fp.read()

fdata = fdata.replace('.',"")

fdata = fdata.replace('-',"")

fdata = fdata.replace(',',"")

fdata = fdata.lower()

Words = fdata.split()

UniqueWords = list(set(Words))

list.sort(UniqueWords)

print("Number of Unique Words = ",len(UniqueWords))

print("Unique Words:")

print(UniqueWords)

finally:

if(fp):

fp.close()


"""

Sample input

Input file: fileipt.txt


File handling in Python has several functions for creating, reading, updating, and deleting files. Read - Default value. Opens a file for reading, error if the file does not exist. Append - Opens a file for appending, creates the file if it does not exist. Write - Opens a file for writing, creates the file if it does not exist. Create - Creates the specified file, returns an error if the file exists.


>python File9.py

Number of Unique Words =  36

Unique Words:

['a', 'an', 'and', 'append', 'appending', 'create', 'creates', 'creating', 'default', 'deleting', 'does', 'error', 'exist', 'exists', 'file', 'files', 'for', 'functions', 'handling', 'has', 'if', 'in', 'it', 'not', 'opens', 'python', 'read', 'reading', 'returns', 'several', 'specified', 'the', 'updating', 'value', 'write', 'writing']


"""



No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu