Python str.islower() 方法似乎在我的代码中不起作用?



我正在通过古腾堡项目网站分析《麦克白》的文本,并试图通过提及角色的名字来创建一个角色列表。我知道nltk有一种方法可以做到这一点,但目前我正在努力避免这种情况。我通过在文本中查找"Enter"的所有实例来获取名称,然后尝试删除所有小写单词。这是我迄今为止的代码:

import requests
macbeth = requests.get('http://www.gutenberg.org/cache/epub/2264/pg2264.txt').text
macbeth = macbeth.split('.')
character_list = [sentence.split() for sentence in macbeth if 'Enter' in sentence]
for sublist in character_list:
for string in sublist:
if string.islower() == True:
sublist.remove(string)

以下是我打印结果时得到的输出摘录:

[['Enter', 'Witches'],
['Enter',
'King,',
'Malcome,',
'Donalbaine,',
'Lenox,',
'attendants,',
'a',
'Captaine'],
['Enter', 'Rosse', 'Angus'],
['Enter', 'three', 'Witches'],
['Enter', 'Macbeth', 'Banquo'],
["Toth'", 'tune', 'words:', 'here?', 'Enter', 'Rosse', 'Angus']
etc.

我很难理解为什么"服务员"、"a"、"三个"、"曲调"等没有从每个子列表中删除。我当前拥有的代码中是否缺少某些内容?

在一个for循环中从列表中删除一项,列表也发生了更改。因此,在这个for string in sublist中,字符串将不会按照原始子列表的顺序循环。

相关内容

最新更新