下面提到的语法是什么意思?

2024-10-04 09:18:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发著名的哈姆雷特机器人程序,以使用python3.7。所以我有一个著名的莎士比亚哈姆雷特戏剧的部分脚本(以字符串输入的形式)。你知道吗

我的任务是将剧本中的句子分成几个列表,然后进一步创建句子中的单词列表。你知道吗

我正在使用从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 

''

在这里我想了解最后两行代码的含义。你知道吗

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

如果有人能帮我的话???你知道吗


Tags: oftheto代码in列表forif
2条回答

假设hamsplits是一个3D数组。你知道吗

第一行检查最后一个平面的最后一行中的最后一个元素是否为点,然后从最后一行中删除最后一个元素

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

应该有同样的效果

del hamsplits[-1][-1][-1]

举个例子,假设我们有像这样的火腿

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

希望这有帮助!你知道吗

相关问题 更多 >