方法1:使用列表添加每个字符,最后将列表拼接成字符串
import string
def removePunctuation(text):
temp = []
for c in text:
if c not in string.punctuation:
temp.append(c)
newText = ''.join(temp)
print(newText)
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:A man a plan a canal Panama
import string
def removePunctuation(text):
ls = []
for item in text:
if item.isdigit() or item.isalpha():
ls.append(item)
print("".join(ls))
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:AmanaplanacanalPanama
方法2:join传递参时计算符合条件的字符
import string
def removePunctuation(text):
b = ''.join(c for c in text if c not in string.punctuation)
print(b)
text = "A man, a plan, a canal: Panama"
removePunctuation(text)
结果为:A man a plan a canal Panama
本文介绍了两种有效的方法来去除Python字符串中的标点符号。第一种方法是通过遍历字符串并检查每个字符是否属于标点符号,然后将非标点字符添加到列表中,最后将列表转换为字符串。第二种方法则更为简洁,直接使用join方法和条件表达式来过滤掉标点符号。这些技巧对于处理文本数据和预处理自然语言处理任务特别有用。
879

被折叠的 条评论
为什么被折叠?



