我需要从标点符号中删除我的文字 - 我正在考虑让函数查看每个单词,并通过从[-1]开始,索引为-1,然后在点击字母后立即从标点符号中拆分单词来确定其中是否有标点符号而不是标点符号......
sent=['I', 'went', 'to', 'the', 'best', 'movie!','Do','you', 'want', 'to', 'see', 'it', 'again!?!']
import string
def revF(List):
for word in List:
for ch in word[::-1]:
if ch is string.punctuation:
#go to next character and check if it's punctuation
newList= #then split the word between the last letter and first puctuation mark
return newList
答案 0 :(得分:1)
如果你想要的只是从字符串中删除标点符号。 Python提供了更好的方法 -
>>> import string
>>> line
'I went to the best movie! Do you want to see it again!?!'
>>> line.translate(None, string.punctuation)
'I went to the best movie Do you want to see it again'
答案 1 :(得分:0)
从您的示例中,我认为您希望将字符串拆分为空格。你可以这么简单地做到这一点:
my_str = "I went to the best movie! Do you want to see it again!?!"
sent = my_str.split(' ')
答案 2 :(得分:0)
使用包含要拆分的标点符号的正则表达式:
re.split('re.split(r"[!?.]", text)
演示:
>>> import re
>>> re.split(r"[!?.]", 'bra det. där du! som du gjorde?')
['bra det', ' d\xc3\xa4r du', ' som du gjorde', '']