【问题标题】:Trying to remove items from list of strings but get the error list.remove(x): x not in list试图从字符串列表中删除项目但得到错误 list.remove(x): x not in list
【发布时间】:2021-02-21 17:40:29
【问题描述】:

我正在尝试编写一个函数,该函数返回字符串中三个最常用单词的列表,但是当我尝试从字符串中删除不需要的标点符号时出现以下错误 "list.remove(x): x not在列表中”

例如,"//wont won't won't " 应该返回 ["won't", "wont"] 或 "a a a b c c d d d e e e e e" 应该返回 ["e", "d", "a"]有什么想法吗?


def top_3_words(text):
    
    new_list = []
    
    new_text = text.lower().split()
    
    for word in new_text:
        for char in word:
            if char.isalpha():
                pass   
            else:
                new_text.remove(char)
             


    Count = Counter(new_text)
    most_occur = Count.most_common(3)
    
    for l in most_occur:
        new_list.append(l[0])
    
    return new_list

【问题讨论】:

  • 你的输出不清楚,写清楚点。
  • new_text 是一个列表["//wont", "won't", "won't"],只有当它们出现在您的列表中时,您才能删除它们。在您的情况下,元素是"//wont""won't"。但是您正在尝试从列表中删除列表中存在的元素的字符,即 "/" 这是不正确的。因此,出现错误:“list.remove(x): x not in list”

标签: python list nested-lists


【解决方案1】:

有几个问题。 1.如果要删除字符串中的字符,则需要将其替换为''。 2. 你的 Counter 仍然指向你的 new_text 列表,而不是你剥离的单词。最后,在每个字符上调用 isalpha 将去掉“不会”中的撇号,我假设你不想要。这是一种不同的方法。您可以根据需要链接尽可能多的 .replace 语句,以消除所有不需要的标点符号。

from collections import Counter
def top_3_words(text):
    new_list = []
    new_text = text.lower().split()
    stripped_words = []

    for word in new_text:
        word = word.replace('/','')
        stripped_words.append(word)

    Count = Counter(stripped_words)
    most_occur = Count.most_common(3)

    for l in most_occur:
        new_list.append(l[0])

    return new_list

print(top_3_words("//wont won't won't "  ))
print(top_3_words("a a a b c c d d d d e e e e e"))

#output:
["won't", 'wont']
['e', 'd', 'a']

更一般地说,您可以创建一个不需要的标点符号列表并按如下方式遍历它:

unwanted = ['.','/',';',':',',']
stripped_words = []

for word in new_text:
    for punc in unwanted:
        word = word.replace(punc, '')
    stripped_words.append(word)

...
print(top_3_words("//wo;nt wo:n't won't... "  ))
#output: ["won't", 'wont']

【讨论】:

  • 这解决了 //won't 的问题,但我希望它也能用于删除其他标点符号。例如: " , e .. " 应该只返回 ["e"]
  • 正如我之前所说,您可以链接尽可能多的替换方法,以摆脱所有不需要的标点符号并保留想要的标点符号。例如,要去掉句号,你可以这样做: word = word.replace('/','').replace('.','')
  • @kabir.987。有关更通用的解决方案,请参阅我的修正答案。以下是 Stack Overflow 上有人帮助您解决问题时的礼仪规则:stackoverflow.com/help/someone-answers
【解决方案2】:

请小心,因为您正试图从 new_text 中删除 char,但 char 是字符串 word 中的一个字符。

如果要删除不需要的字符,可以执行以下操作: 而不是使用

new_text.remove(char)

你可以使用

word = word.replace(char, '')

此代码的作用是将不需要的字符替换为空字符串。

您遇到的另一个问题是 ' 将在 char.isalpha() 中返回 False,因此“不会”将转换为“不会”并从 "//不会不会不会" 你只会得到 ["wont"]

如果您想要删除带有不需要字符的单词,则必须使用:

 new_text.remove(word)
 break

【讨论】:

  • 嗨,这行不通。 new_text 是一个列表,而不是一个字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-23
  • 2022-06-28
  • 2021-11-03
  • 1970-01-01
  • 2022-06-11
  • 2020-07-11
  • 1970-01-01
相关资源
最近更新 更多