【问题标题】:How do I remove punctuation from an item in a list and save it as a separate item in the list?如何从列表中的项目中删除标点符号并将其另存为列表中的单独项目?
【发布时间】:2016-10-16 10:33:54
【问题描述】:

我正在尝试将项目从一个列表压缩到另一个列表,我需要能够将标点符号保存为列表中的单独项目,因为如果我不这样做,“你”和“你;”在列表中保存为单独的项目。

例如原始列表是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President.']

压缩列表目前是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'you', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'former', 'American', 'President.']

但我希望它在列表中具有标点符号作为单独的项目。

我的预期输出是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask', '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'former', 'American', 'President', '.']

【问题讨论】:

  • 请举一些例子。
  • 你的预期输出是什么?
  • 你的意思是[re.sub(r'[:?.!]', '', s) for s in lst]
  • 对不起,我不知道该怎么办

标签: python arrays list arraylist compression


【解决方案1】:

您可以使用regex 来实现。

import re
a = ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President.']
result = re.findall(r"[\w']+|[.,!?;]",' '.join(a))

输出

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country', '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President', '.']

这里有一个演示,可以进一步了解regex

【讨论】:

  • 看起来不错,但我仍然无法让它工作。也许是因为我不知道该放在哪里。
  • 您的输入是a 对(在我的回答中指定)。你究竟把这个和平的代码放在哪里。
【解决方案2】:

这是分隔非字母字符并删除重复项的代码。希望有帮助。

def separate(mylist):
    newlist = [] 
    test = ''
    a = ''
    for e in mylist:
        for c in e:   
            if not c.isalpha():
                a = c
            else:
                test = test + c
        if a != '':
            newlist = newlist + [test] + [a]
        else:
            newlist = newlist + [test]
        test = ''
        a = ''
    noduplicates = []
    for i in newlist:
        if i not in noduplicates:
            noduplicates = noduplicates + [i]
    return noduplicates

我相信其他人可以做得更好,因为这有点混乱,但至少有效。

【讨论】:

  • 他不想删除字母字符。他只是想把标点和单词分开,做成单独的列表。
  • 不想删除它们,我想将它们另存为列表中的单独项目
  • 哦,好的,请稍等
猜你喜欢
  • 2023-03-12
  • 2015-05-25
  • 2018-12-11
  • 1970-01-01
  • 2017-09-09
  • 2011-05-21
  • 1970-01-01
  • 2022-12-20
  • 2021-03-12
相关资源
最近更新 更多