Python从文本文件中删除标点符号

时间:2016-12-19 15:02:18

标签: python list punctuation

我试图从我的文本文件中删除标点符号列表,但我只有一个问题,即从连字符分隔的单词。例如,如果我有"创伤后"我得到" posttrama"相反,我想得到" post" "创伤"

我的代码是:

 punct=['!', '#', '"', '%', '$', '&', ')', '(', '+', '*', '-'] 

 with open(myFile, "r") as f:
      text= f.read()
      remove = '|'.join(REMOVE_LIST) #list of word to remove
      regex = re.compile(r'('+remove+r')', flags=re.IGNORECASE) 
      out = regex.sub("", text)

      delta= " ".join(out.split())
      txt = "".join(c for c in delta if c not in punct )

有没有办法解决它?

2 个答案:

答案 0 :(得分:3)

我相信您可以在delta上调用内置的replace函数,因此您的最后一行将成为以下内容:

txt = "".join(c for c in delta.replace("-", " ") if c not in punct )

这意味着文本中的所有连字符都将成为空格,因此这些单词将被视为分开。

答案 1 :(得分:0)

上述方法可能无效,因为您仍然从初始字符串中删除所有短划线(“ - ”)字符。如果您希望它工作,请从列表punct中删除它。更新后的代码如下所示:

punct=['!', '#', '"', '%', '$', '&', ')', '(', '+', '*'] 

 with open(myFile, "r") as f:
      text= f.read()
      remove = '|'.join(REMOVE_LIST) #list of word to remove
      regex = re.compile(r'('+remove+r')', flags=re.IGNORECASE) 
      out = regex.sub("", text)

      delta= " ".join(out.split())
      txt = "".join(c for c in delta.replace("-", " ") if c not in punct )

问题来自于您用空字符串替换punct中的所有字符,并且您想要“ - ”的空格。因此,您需要将字符替换两次(一次使用空字符串,一次使用空格)。

相关问题