如何从列表项中删除标点符号并将其保存为列表中的单独项?

4
我正在尝试将一个列表中的项目压缩到另一个列表中,我需要能够将标点符号保存为列表中的单独项,因为如果不这样做,“you”和“you;”会被保存为列表中的单独项。
例如,原始列表是:
['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', '.']

请举一些例子。 - Rahul K P
你期望的输出是什么? - Avinash Raj
你的意思是 [re.sub(r'[:?.!]', '', s) for s in lst] - Avinash Raj
对不起,我不确定该怎么处理那个。 - Nick Davies
2个回答

2
你可以使用正则表达式实现。
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', '.']

这是一个演示,以更好地了解正则表达式

看起来不错,但我仍然无法让它工作。也许是因为我不知道该放在哪里。 - Nick Davies
你的输入是 a 对吧(在我的答案中指定)。你要把这段代码放在哪里? - Rahul K P

0
这是用于分离非字母字符并删除重复项的代码。希望能对您有所帮助。
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

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


他不想删除字母字符,只是想将标点符号与单词分开,并制成单独的列表。 - Rahul K P
不想删除它们,我想将它们作为列表中的单独项目保存。 - Nick Davies
哦,好的,请稍等一下。 - Doni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接