我正在使用Python 3.7开发著名的hamlet bot程序。因此,我有一部著名的莎士比亚戏剧《哈姆雷特》剧本的部分剧本(以字符串输入的形式)。
我的任务是将脚本的句子分成列表,然后进一步创建句子中单词的列表。
我正在使用从互联网复制的以下代码:
'''
Error in pivot_longer(., cols = starts_with("hf"), names_to = "hf_com", :
unused argument (na.rm = TRUE)
'''
在这里,我想了解代码的最后两行的含义。
### 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
如果有人可以帮助我吗?
答案 0 :(得分:0)
让我们假设hamsplits
是一个3D数组。
第一行检查最后一个平面的最后一行中的最后一个元素是点,然后从最后一行中删除该最后一个元素
>>> x = [1, 2, 3]
>>> x = x[:-1] # Remove last element
>>> x
[1, 2]
应该与
具有相同的效果del hamsplits[-1][-1][-1]
答案 1 :(得分:0)
让我们举个例子,假设我们有类似的障碍
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
希望这会有所帮助!