在嵌套列表python中去除专有名词

2024-06-16 14:48:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图纠正一个接受嵌套列表的程序,并返回一个去掉专有名词的新列表。在

下面是一个例子:

L = [['The', 'name', 'is', 'James'], ['Where', 'is', 'the', 'treasure'], ['Bond', 'cackled', 'insanely']]

我想回来:

^{pr2}$

请注意,“where”已删除。它没有问题,因为它不会出现在嵌套列表中的任何其他位置。每个嵌套列表都是一个句子。我的方法是将嵌套列表中的每个第一个元素追加到一个newList。然后比较newList中的元素是否在嵌套列表中。我会将newList中的元素小写以进行检查。这个程序已经完成了一半,但是当我试图从末尾的newList中删除元素时,我遇到了一个错误。获得新的更新列表后,我想从newList中的嵌套列表中删除项。最后,我将嵌套列表中的所有项附加到一个newerList并将它们小写。那应该行了。在

如果有人有更有效的方法,我很乐意倾听。在

^{3}$

注意,由于倒数第二行的错误,此代码未完成

以下是newerList(updatedNewList)的信息:

def lowerCaseFirst(L):
    newList = []
    for nestedList in L:
        newList.append(nestedList[0])
    print newList
    updatedNewList = newList
    for firstWord in newList:
        sum = 0
        firstWord = firstWord.lower()
        for nestedList in L:
            for word in nestedList[1:]:
                if firstWord == word:
                    print "yes"

                    sum = sum + 1
            print newList
        if sum >= 1:
            firstWord = firstWord.upper()
            updatedNewList.remove(firstWord)
    return updatedNewList

错误消息:

Traceback (most recent call last):
  File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
    # Used internally for debug sandbox under external interpreter
  File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 80, in lowerCaseFirst
ValueError: list.remove(x): x not in list

Tags: indebug程序元素列表foris错误
1条回答
网友
1楼 · 发布于 2024-06-16 14:48:15

第一个函数中的错误是因为您试图从newlist中删除firstWord的大写版本,其中没有大写单词(从打印输出中可以看到)。请记住,您将单词的大小写版本存储在一个新变量中,但不会更改原始列表的内容。在

我还是不明白你的做法。当你描述你的任务时,你想做的事情是:1)把列表的列表展平成元素列表(总是一个有趣的编程练习);2)从这个列表中删除专有名词。这意味着你必须决定什么是专有名词。您可以简单地这样做(所有非起始大写的单词,或者一个详尽的列表),或者您可以使用POS标记器(参见:Finding Proper Nouns using NLTK WordNet)。除非我完全误解了你的任务,否则你不必担心这里的外壳。在

第一个任务可以用很多方法来解决。这里有一个很好的方法,很好地说明了在这个简单的例子中实际发生了什么,其中list L是一个列表的列表(而不是可以无限嵌套的列表):

def flatten(L):
  newList = []
  for sublist in L:
      for elm in sublist: 
          newList.append(elm)
  return newList

通过检查每个元素,可以将此函数转换为flattendfilter(L):

PN=['James','Bond']

^{pr2}$

但是,您可能没有这么好的pn列表,那么您必须扩展检查,例如通过解析句子和检查POS标记。在

相关问题 更多 >