首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >下面提到的语法是什么意思?

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

Stack Overflow用户
提问于 2019-09-26 19:21:51
回答 2查看 73关注 0票数 0

我正在用Python3.7编写著名的hamlet机器人程序。因此,我有一个来自莎士比亚著名哈姆雷特戏剧的部分脚本(以字符串输入的形式)。

我的任务是将脚本中的句子分成列表,然后进一步创建句子中单词的列表。

我正在使用从互联网上复制的以下代码:

“”“

代码语言:javascript
复制
### 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 

“”“

在这里,我想要理解代码最后两行的含义。

代码语言:javascript
复制
if hamsplits[-1][-1][-1] == '.':
        hamsplits[-1][-1] = hamsplits[-1][-1][:-1] # Remove trailing punctuation 

如果有人能帮我的话?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-09-26 19:27:08

让我们假设hamsplits是一个3D数组。

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

代码语言:javascript
复制
>>> x = [1, 2, 3]
>>> x = x[:-1] # Remove last element
>>> x
[1, 2]

应该具有与

代码语言:javascript
复制
del hamsplits[-1][-1][-1]
票数 0
EN

Stack Overflow用户

回答已采纳

发布于 2019-09-26 19:27:08

让我们举个例子,假设我们有如下的腿裂

代码语言:javascript
复制
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

希望这能有所帮助!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58115722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档