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

Python str.islower() method doesn't seem to be working in my code?

我正在通过 Project Gutenberg 网站分析 Macbeth 的文本,并试图通过提及他们的名字来创建角色列表。我知道有一种方法可以用 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.

我很难理解为什么 'attendants'、'a'、'three'、'tune' 等没有从每个子列表中删除。我是否遗漏了我当前拥有的代码中的某些内容?

您在一个 for 循环中从列表中删除了一项,列表也发生了变化。所以在这个for string in sublist中,字符串不会按照原来子列表的顺序循环。