python - Python str.islower() 方法似乎在我的代码中不起作用?
问题描述
我正在通过 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
中,字符串不会按照原始子列表的顺序循环。
推荐阅读
- scala - 实木复合地板到 csv 转换后日期发生变化
- canvas - 画布绘制对角 CSS 渐变
- dataframe - KeyError:“[索引(['MW','LogP','NumAromatic','HBD','HBA'],dtype ='object')]中没有[列]”
- xml - 更新 xml 文件的每个部分中的条目
- asp.net-core - 如何将新的 userId roleId 添加到 AspNetUserRoles 表并从 AspNetUserRoles 表中删除一行?
- typescript - 如何将打字稿添加到现有的 vue3 项目?
- c# - C#:通过异构字典公开类型安全 API
- firebase - 关于firebase监听器和定价的问题
- mysql - mysqladmin:[错误] mysqladmin:指定了“端口”的空值
- c++ - C ++屏蔽字符串的所有字符,除了最后n个字符