In: Computer Science
Python Project Description: Text Processing
This assignment requires you to process a short text from an input file, perform some analyses, manipulate the text, and save the results in an output file. For example, the input file bentley.txt contains a brief introduction of Bentley University:
Each line in this file is a paragraph that contains one or more sentences. Note that each line can be very long!
The program will provide the following user interaction on the screen:
· Ask the user to enter the name of the input file that contains the document.
· Ask the user to enter the width of the line in the output file.
· Ask the user to enter a pattern (e.g., ‘on’).
· Ask the user for enter a new pattern (e.g., ‘@@’) that is used to replace the old pattern.
· Ask the user to choose Left/Right/Center justification for the output.
· Display a message showing the name of the output file written.
Below is a screen shot of the python program to check indentation. Comments are given on every line explaining the code.Below is the output of the program: Contents of Bentley.txt:
Console output:
Contents of Bentley_output.txt:
Below is the code to copy: #CODE STARTS HERE----------------
import io #Used to loop paragraphs by "\n" as delimiter
#input all details here
file_input = input("Enter the file name: ")
line_width = int(input("Enter line width: "))
pattern_in = input("Enter the pattern to change: ")
pattern_out = input("Enter the pattern to replace the old pattern: ")
justification = input("Enter justification (Left/Right/Center): ")
#Open file and read text.
f = open(file_input,"r")
paragraph = f.read().replace(pattern_in,pattern_out) #replace pattern
f.close() #close file
#Add "\n" if the line is longer than line_width
modified_para = ""
for x in io.StringIO(paragraph): #loop through every line in the paragraph
if len(x)>line_width: #Check length
li = []
for i in range(0, len(x), line_width): #If line is greater than line_width
li.append(x[i:i + line_width]) #Add '\n' after every line_width number of chars
modified_para += '\n'.join(li)
else:
modified_para+= x
#Modify output file name and print it
file_output = file_input.split(".")[0]+"_output."+file_input.split(".")[-1]
print("\nThe output file is",file_output)
#Open output file
f_out = open(file_output,"a+")
#If left justify
if justification.strip().lower() == "left":
for x in io.StringIO(modified_para):
f_out.write("{:<{y}}\n".format(x.strip(),y = line_width)) #Use "{:<}".format to left justify
if justification.strip().lower() == "right":
for x in io.StringIO(modified_para):
f_out.write("{:>{y}}\n".format(x.strip(),y = line_width)) #Use "{:>}".format to right justify
if justification.strip().lower() == "center":
for x in io.StringIO(modified_para):
f_out.write("{:^{y}}\n".format(x.strip(),y = line_width)) #Use "{:^}".format to center justify
f_out.close() #close file
#CODE ENDS HERE------------------