gpt4 book ai didi

python - 使用Python从列表中删除标点符号/符号(句点、逗号除外)

转载 作者:行者123 更新时间:2023-12-01 03:39:06 25 4
gpt4 key购买 nike

在 Python 中,我需要从列表中删除几乎所有标点符号,但保留句点和逗号。我应该创建一个函数来执行此操作还是创建一个变量?基本上我想删除除字母(我已经将大写字母转换为小写)以及句点和逗号(可能还有撇号)之外的所有符号。

#Clean tokens up (remove symbols except ',' and '.')

def depunctuate()
clean_tokens = []

for i in lc_tokens:
if (i not in [a-z.,])
...

最佳答案

您可以从 string.punctuation 构建一组不需要的标点符号- 它提供一个包含标点符号的字符串,然后使用列表理解来过滤掉集合中包含的字母:

import string

to_delete = set(string.punctuation) - {'.', ','} # remove comma and fullstop
clean_tokens = [x for x in lc_tokens if x not in to_delete]

关于python - 使用Python从列表中删除标点符号/符号(句点、逗号除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39946660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com