【问题标题】:Python str.islower() method doesn't seem to be working in my code?Python str.islower() 方法似乎在我的代码中不起作用?
【发布时间】:2018-12-16 05:03:44
【问题描述】:

我正在通过 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' 等没有从每个子列表中删除。我当前拥有的代码中是否缺少某些内容?

【问题讨论】:

  • 您应该检查单个单词。到目前为止,您似乎正在检查整个句子。试试character_list = [s for sentence in macbeth if 'Enter' in sentence for s in sentence.split() if not s.islower() and s not in {'Enter', '&'}]
  • 这行得通。谢谢!

标签: python python-requests lowercase


【解决方案1】:

您在一个 for 循环中从列表中删除一项,列表也已更改。所以在这个for string in sublist中,字符串不会按照原始子列表的顺序循环。

【讨论】:

  • 换句话说,不要在迭代列表时从列表中删除项目。
  • 知道了。那讲得通。我猜如果不指定需要删除的停用词,就无法迭代地实现我想要做的事情。
猜你喜欢
  • 2017-12-22
  • 2019-08-06
  • 1970-01-01
  • 2019-12-21
  • 2012-08-25
  • 1970-01-01
  • 2023-02-04
  • 2015-03-25
  • 1970-01-01
相关资源
最近更新 更多