尝试在python中删除以下标点符号我需要使用replace方法删除这些标点字符并用空格替换它,。:;'“ - ?!/
这是我的代码:
text_punct_removed = raw_text.replace(".", "")
text_punct_removed = raw_text.replace("!", "")
print("\ntext with punctuation characters removed:\n", text_punct_removed)
它只会删除我尝试替换的最后一个,所以我尝试将它们组合起来
text_punct_removed = raw_text.replace(".", "" , "!", "")
print("\ntext with punctuation characters removed:\n", text_punct_removed)
但是我收到错误消息,如何删除多个标点符号?如果我把“像这样的”引号“”“也会有问题,这会引起评论,有没有办法解决这个问题呢?感谢
答案 0 :(得分:1)
这是一个天真但有效的解决方案:
for sp in '.,"':
raw_text = raw_text.replace(sp, '')
答案 1 :(得分:1)
如果您需要用空格替换所有标点符号,可以使用内置标点符号列表来替换字符串:
Python 3
import string
import re
my_string = "(I hope...this works!)"
translator = re.compile('[%s]' % re.escape(string.punctuation))
translator.sub(' ', my_string)
print(my_string)
# Result:
# I hope this works
之后,如果你想删除字符串中的双重空格,你可以:
my_string = re.sub(' +',' ', my_string).strip()
print(my_string)
# Result:
# I hope this works
答案 2 :(得分:1)
这适用于Python3.5.3:
from string import punctuation
raw_text_with_punctuations = "text, with: punctuation; characters? all over ,.:;'\"-?!/"
print(raw_text_with_punctuations)
for char in punctuation:
raw_text_with_punctuations = raw_text_with_punctuations.replace(char, '')
print(raw_text_with_punctuations)
答案 3 :(得分:0)
一次删除一个字符:
raw_text.replace(".", "").replace("!", "")
或者,更好的是,使用正则表达式(re.sub()
):
re.sub(r"\.|!", "", raw_text)
答案 4 :(得分:0)
如果您不需要明确使用replace:
exclude = set(",.:;'\"-?!/")
text = "".join([(ch if ch not in exclude else " ") for ch in text])