Question

Please solve in python and provide comments explaining your codes. Your output must be the same as the example and result given below in the images.

This task is to write a very basic text editor. It allows you to add, delete and modify lines of text.  Use a list of strings to store the lines, with each list element being one line. The elements of the list are modified according the commands given by the user.

The editor repeatedly:
1.    displays the lines entered so far prefixed with a line number in front of each and ending with an empty line.
2.    it waits for the user to enter a command
3.    if it's a valid command, it modifies the list appropriately
4.    go back to step #1

Initially, the list of lines will be empty.

You should have a function for each of the commands below, except for Quit.

The valid commands are:

  • a - add a line
    Lines from the user are added to the lines collected so far. All lines entered are added to the list until the user enters a line containing a single #.
  • d - delete a line
    Prompt for a line number and then delete that line. Use the Python command del to delete a line from the list of lines. Check that the line number entered is valid. If it is invalid, ask for a line number again.
  • r - replace a line
    Prompt for a line number and then replace that line with a new one from the user. Check that the line number entered is valid. If it is invalid, ask for a line number again.
  • f - find and replace a string
    Prompt for one string (the search pattern) and then a second (the replacement). Replace all occurrences of the first string with the second, using string.replace() .
  • p – copy/paste lines
    Prompt for two line numbers, one is the starting line of text to copy, and the second is the end line of the text to copy. Slice this part of the list, and add it to the end of the list as a single string.
    Check that the line numbers entered are valid. If they are invalid, ask for a line numbers again.
  • c - Clear all
    Delete all lines, so the state is like when the program starts.
  • q - Quit
    End the program.

***Clarification on line numbers*** You can expect that any line numbers entered for the above functions are integers. You do NOT need to test if they are non-integer inputs, but just that they are in range of the line numbers that exist.

Here's an example of this editor in use. Several commands are shown. Initially, before the 'a' (add) command is used, there aren't any lines, so nothing is output before the command prompt.

Command a, d, r, f, p, c, q: a
Add a line: It is a lovely morning
Add a line: for a walk.
Add a line: It is a lovely evening
Add a line: for reading a book
Add a line: in front of the fire.
Add a line: #
1: It is a lovely morning
2: for a walk.
3: It is a lovely evening
4: for reading a book
5: in front of the fire.

Command a, d, r, f, p, c, q: d
Line number: 5
1: It is a lovely morning
2: for a walk.
3: It is a lovely evening
4: for reading a book

Command a, d, r, f, p, c, q: r
Replace line number: 2
Replacement string: for a walk in the park.
1: It is a lovely morning
2: for a walk in the park.
3: It is a lovely evening
4: for reading a book

Command a, d, r, f, p, c, q: f
Find string: lovely
Replace with: wonderful
1: It is a wonderful morning
2: for a walk in the park.
3: It is a wonderful evening
4: for reading a book

Command a, d, r, f, p, c, q: p
Start line number: 7
End line number: 8
Start line number: 1
End line number: 2
1: It is a wonderful morning
2: for a walk in the park.
3: It is a wonderful evening
4: for reading a book
5: It is a wonderful morning for a walk in the park.

Command a, d, r, f, p, c, q: c

Command a, d, r, f, p, c, q: q

For example: Input Result a It is a lovely morning for a walk. It is a lovely evening for reading a book in front of the fire

Command a, d, r, f, P, C, a: f Find string: lovely Replace with: wonderful 1: It is a wonderful morning 2: for a walk in the

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

CODE:

# list to store the lines
lines = []

# function to add lines
def add_lines():

    # infinite looping
    while True:

        # getting input from the user
        line=input('Add a line: ')

        # break when input is #
        if line == '#':
            break
        else:

            # adding line to the list
            lines.append(line)

# function to delete a line
def delete_line():

    # infite looping
    while True:

        # getting line number
        num = int (input('Line number: '))

        # checking for valid line number
        if num >=1 and num <=len(lines):

            # deleting the line
            del lines[num-1]
            break
        else:
            print('Invalid line number. Try again.')

# function to replace line with another line
def replace_line():

    # infite looping
    while True:

        # replacement line number input
        replace = int(input('Replace line number: '))

        # checking for valid line number
        if replace >=1 and replace <=len(lines):

            # getting replacement string
            replacement = input('Replacement string: ')

            # deleting the line
            del lines[replace-1]

            # inserting the line
            lines.insert(replace-1,replacement)
            break
    
        else:
            print('Invalid line number. Try again.')

# function to find and replace string
def find_replace():

    # getting user input
    find = input('Find string: ')
    replace = input('Replace with: ')

    # looping through lines
    for num in range(len(lines)):

        # replacing the string
        lines[num]=lines[num].replace(find,replace)

# function to copy and paste
def copy_paste():

    # infite looping
    while True:

        # getting line numbers
        start=int(input('Start line number: '))

        end = int(input('End line number: '))

        # variable to store string
        s=''

        # checking for valid line number
        if start >=1 and start <=len(lines) and start< end and end >=1 and end <=len(lines):

            # getting string from list
            for line in lines[start-1:end]:            
                s+=line+' '

            # adding the line to end of the list
            lines.append(s)
            break

# function to clear the list
def clear_all():

    lines.clear()
    print('\n')

# infite looping
while True:

    # printing the lines from the list if not empty
    if lines:

        num = 0

        for i in lines:
            num +=1
            print('%d: %s' % (num,i))
        print('\n')

    # getting user choice
    choice = input('Command a, d, r, f, p, c, q: ')

    # calling the functions based on the choice of the user
    if choice == 'a':

        add_lines()

    elif choice == 'd':

        delete_line()

    elif choice == 'r':
        replace_line()

    elif choice == 'f':

        find_replace()

    elif choice == 'p':
        copy_paste()

    elif choice == 'c':
        clear_all()

    elif choice == 'q':
        break

    else:
        print('Enter a valid choice')

SCREENSHOT OF THE CODE:

1 2 # list to store the lines lines = [] 3 4 # function to add lines 5def add_lines(): 6 7 # infinite looping 8 v while True:else: print(Invalid line number. Try again.) # function to replace line with another line def replace_line(): # infite loop# function to find and replace string def find_replace(): # getting user input find = input(Find string: ) replace = input(# adding the line to end of the list lines.append(s) break # function to clear the list def clear_all(): lines.clear() print(elif choice == r: replace_line() elif choice == f: find_replace() 132 133 134 135 136 137 138 139 140 141 142 143 144 145

OUTPUT:

input Command a, d, r, f, P, C, q: a Add a line: It is a lovely morning Add a line: for a walk. Add a line: It is a lovely evCommand a, d, r, f, p, c, q: r Replace line number: 2 Replacement string: for a walk in the park. 1: It is a lovely morning 2Command a, d, r, f, P, c, q: p Start line number: 7 End line number: 8 Start line number: 1 End line number: 2 1: It is a won

I have done it by using Python 3.

Thank you.

Add a comment
Know the answer?
Add Answer to:
Please solve in python and provide comments explaining your codes. Your output must be the same...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • JAVA DATA STRUCTURES Write a line-based text editor. The command syntax is similar to the Unix...

    JAVA DATA STRUCTURES Write a line-based text editor. The command syntax is similar to the Unix line editor ed. The internal copy of the file is maintained as a linked list of lines. To be able to go up and down in the file, you have to maintain a doubly linked list. Most commands are represented by a one-character string. Some are two characters and require an argument (or two). Support the commands shown below: Command Function Go to the...

  • Hello, I have some errors in my C++ code when I try to debug it. I...

    Hello, I have some errors in my C++ code when I try to debug it. I tried to follow the requirements stated below: Code: // Linked.h #ifndef INTLINKEDQUEUE #define INTLINKEDQUEUE #include <iostream> usingnamespace std; class IntLinkedQueue { private: struct Node { int data; Node *next; }; Node *front; // -> first item Node *rear; // -> last item Node *p; // traversal position Node *pp ; // previous position int size; // number of elements in the queue public: IntLinkedQueue();...

  • MUST USE C++ PLEASE READ THE QUESTION CAREFULLY ADD COMMENTS AND EXPLAIN THE CODES PLEASE. Given...

    MUST USE C++ PLEASE READ THE QUESTION CAREFULLY ADD COMMENTS AND EXPLAIN THE CODES PLEASE. Given the following skeleton of an unsorted list class that uses an unsorted linked list: template < class ItemType > struct NodeType {                 ItemType item;                 NodeType* next; }; template < class ItemType > class UList { public:                 UList(); // default constrctor                 UList(const UList &x); // we implement copy constructor with deep copy                 UList& operator = (UList &x); // equal sign...

  • Please use C programming to write the code to solve the following problem. Also, please use the i...

    Please use C programming to write the code to solve the following problem. Also, please use the instructions, functions, syntax and any other required part of the problem. Thanks in advance. Use these functions below especially: void inputStringFromUser(char *prompt, char *s, int arraySize); void songNameDuplicate(char *songName); void songNameFound(char *songName); void songNameNotFound(char *songName); void songNameDeleted(char *songName); void artistFound(char *artist); void artistNotFound(char *artist); void printMusicLibraryEmpty(void); void printMusicLibraryTitle(void); const int MAX_LENGTH = 1024; You will write a program that maintains information about your...

  • ****************************************************************************************************************8 I want it same as the output and with details please and comments "For two...

    ****************************************************************************************************************8 I want it same as the output and with details please and comments "For two thousand years, codemakers have fought to preserve secrets while codebreakers have tried their best to reveal them." - taken from Code Book, The Evolution of Secrecy from Mary, Queen of Scots to Quantum Cryptography by Simon Singh. The idea for this machine problem came from this book.You will encrypt and decrypt some messages using a simplified version of a code in the book. The...

  • Please provide original Answer, I can not turn in the same as my classmate. thanks In...

    Please provide original Answer, I can not turn in the same as my classmate. thanks In this homework, you will implement a single linked list to store a list of computer science textbooks. Every book has a title, author, and an ISBN number. You will create 2 classes: Textbook and Library. Textbook class should have all above attributes and also a “next” pointer. Textbook Type Attribute String title String author String ISBN Textbook* next Textbook Type Attribute String title String...

  • Hi, can someone offer input on how to address these 4 remain parts the zybook python...

    Hi, can someone offer input on how to address these 4 remain parts the zybook python questions?   4: Tests that get_num_items_in_cart() returns 6 (ShoppingCart) Your output ADD ITEM TO CART Enter the item name: Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in <module> passed = test_passed(test_passed_output_file) File "/home/runner/local/submission/unit_test_student_code/zyLabsUnitTest.py", line 8, in test_passed cart.add_item(item1) File "/home/runner/local/submission/unit_test_student_code/main.py", line 30, in add_item item_name = str(input('Enter the item name:\n')) EOFError: EOF when reading a line 5: Test that get_cost_of_cart() returns 10 (ShoppingCart)...

  • MUST BE IN PYTHON!!!! PLEASE HELP WITH NUMBER 10 & 11A & 11B!!! WIILL VOTE UP!!!...

    MUST BE IN PYTHON!!!! PLEASE HELP WITH NUMBER 10 & 11A & 11B!!! WIILL VOTE UP!!! F=False boolExprs = [T and F, T or F, T and T, F or F trueCount = 0 for expr in boolExprs: if expr: trueCount += 1 print (trueCount) a. 1 b. 2 c. 3 d. 4 e. None of the above Question 10 import tu1rtle s turtle.Screen () t turtle. Turtle () for i in range 4) if i%2 = 1: t.down )...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT