File word count and longest word

# File handling 

# Word count in file

# Longest word in file


fs = None


try:

fs = open("wcipt.txt","r")

except IOError as e:

print("File opening error : ", e)

except:

print("unknown error")

else:

fdata = fs.read()

print("File data: ")

print(fdata)

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

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

L = fdata.split()

print("Number of words in file = ",len(L))

sortedwords = sorted(L, key=len)

print("Longest word = ",sortedwords[-1] )

print("Length of longest word = ", len(sortedwords[-1]))


finally:

if(fs):

fs.close()


"""

Sample output:

>python fileWC.py


File data:

Pygame is a set of Python modules designed for writing video games. Pygame adds functionality on top of the SDL library. Simple DirectMedia Layer is a cross-platform development library designed to provide low level access to audio, keyboard, mouse, joystick, and graphics hardware via OpenGL and Direct3D. It is used by video playback software, emulators, and popular games. SDL officially supports Windows, Mac OS X, Linux, iOS, and Android.  SDL is written in C, works natively with C++, and there are bindings available for several other languages, including C# and Python. Pygame, together with SDL, allows users to create fully featured games and multimedia programs in the python language. Pygame is highly portable and runs on nearly every platform and operating system.


Number of words in file =  122

Longest word =  cross-platform

Length of longest word =  14

"""


No comments:

Post a Comment

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

Anu