0

I am working on the famous hamlet bot program to in Python 3.7. So I have a partial script (in the form of string input) from the famous Hamlet play of Shakespeare.

My task is to split the sentences of the script into lists and then further create list of the words in the sentences.

I am using the following code copied from the internet:

'''

### BEGIN SOLUTION
def hamsplits__soln0():
    cleanham = ""
    for char in hamlet_text:
        swaplist = ["?","!", "."] #define the puntuations which we need to replace.
        if char in swaplist:
            cleanham += "." #replace all the puntuations with .
        elif char is " ":
            cleanham += char #convert all the spaces to character type.
        elif char.isalpha():
            cleanham += char.lower() #bringing all the letters in lower case.

    hamlist = cleanham.split(". ") #spliting all the sentences as the parts of a list.

    for sentence in hamlist:
        hamsplits.append(sentence.split()) #spliting all the words of the sentences as the part of list.

    if hamsplits[-1][-1][-1] == '.':
        hamsplits[-1][-1] = hamsplits[-1][-1][:-1] # Remove trailing punctuation 

'''

Here in I want to understand the meaning of the last two lines of the code.

if hamsplits[-1][-1][-1] == '.':
        hamsplits[-1][-1] = hamsplits[-1][-1][:-1] # Remove trailing punctuation 

If anyone can help me on this???

2 Answers2

0

Let's suppose that hamsplits it's a 3D array.

The first line check that the last element in the last line of last plane is dot and then remove this last element from the last line

>>> x = [1, 2, 3]
>>> x = x[:-1] # Remove last element
>>> x
[1, 2]

Should have the same effect with

del hamsplits[-1][-1][-1]
P. Dmitry
  • 1,123
  • 8
  • 26
0

Let's take an example, suppose we have hamsplits like

hamsplits=['test',['test1',['test2','.']]]
print(hamsplits[-1][-1][-1])  # it would be equal to '.' 
if hamsplits[-1][-1][-1] == '.':  # here we are comparing it with "."
       hamsplits[-1][-1] = hamsplits[-1][-1][:-1] # in this we are just removing the '.' from third list in hamsplits and taking all remaining elements
print(hamsplits[-1][-1][:-1]) # it would print ['test2'] (removing last element from list) and overwriting in hamsplits[-1][-1]

**Note**:
hamsplits[:-1] is removing the last element, it's a slicing in python
hamsplits[-1] you are accessing the last element

Hope this helps!

Bharat Gera
  • 800
  • 1
  • 4
  • 13