0% found this document useful (0 votes)
3 views2 pages

Python Lab Programs C&D - 5&6

The document provides a Python program that counts and prints the 10 most frequently appearing words in a given text using the Counter class and regular expressions. Additionally, it includes a function to sort the contents of a text file and write the sorted lines back into the same file. The code demonstrates basic file handling and string manipulation in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Python Lab Programs C&D - 5&6

The document provides a Python program that counts and prints the 10 most frequently appearing words in a given text using the Counter class and regular expressions. Additionally, it includes a function to sort the contents of a text file and write the sorted lines back into the same file. The code demonstrates basic file handling and string manipulation in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

5. Develop a program to print 10 most frequently appearing words in a text file.

# Import the Counter class from the collections module


from collections import Counter

# Import the re module for regular expressions


import re

# Define a multi-line text string containing information about


Python
text = """The Python Software Foundation (PSF) is a 501(c)(3)
non-profit corporation that holds the intellectual property
rights behind
the Python programming language. We manage the open source
licensing
for Python version 2.1 and later and own and protect the
trademarks
associated with Python. We also run the North American PyCon
conference annually, support other Python conferences around the
world, and fund Python related development with our grants
program and by funding special projects."""

# Use a regular expression to extract words from the text


words = re.findall('\w+', text)

# Use Counter to count the occurrences of each word in the text


and find the 10 most common words
print(Counter(words).most_common(10))
6. Python program to sort the contents of a text file. Write the sorted contents into a separate text file

def main():

inputFile = open("students1.txt", 'r')

lineList = inputFile.readlines()

lineList.sort()

print (lineList)

for line in lineList:

print(line)

with open('students1.txt', 'a') as f:

for line in lineList:

lineList.sort()

f.write(line)

main()

You might also like