我正在用Python3.7编写著名的hamlet机器人程序。因此,我有一个来自莎士比亚著名哈姆雷特戏剧的部分脚本(以字符串输入的形式)。
我的任务是将脚本中的句子分成列表,然后进一步创建句子中单词的列表。
我正在使用从互联网上复制的以下代码:
“”“
### 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 如果有人能帮我的话?
发布于 2019-09-26 19:27:08
让我们假设hamsplits是一个3D数组。
第一行检查最后一条平面的最后一行中的最后一个元素是否为点,然后从最后一行中删除最后一个元素
>>> x = [1, 2, 3]
>>> x = x[:-1] # Remove last element
>>> x
[1, 2]应该具有与
del hamsplits[-1][-1][-1]发布于 2019-09-26 19:27:08
让我们举个例子,假设我们有如下的腿裂
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希望这能有所帮助!
https://stackoverflow.com/questions/58115722
复制相似问题