【问题标题】:Python remove punctuation from a text filePython从文本文件中删除标点符号
【发布时间】:2016-12-19 15:02:18
【问题描述】:

我正在尝试从我的文本文件中删除标点符号列表,但我只有一个与连字符分隔的单词的问题。例如,如果我有“post-trauma”这个词,我会得到“posttrama”,相反,我想得到“post”“trauma”。

我的代码是:

 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 )

有办法解决吗?

【问题讨论】:

  • 你应该使用正则表达式,你不希望 [a-zA-Z].*-[a-z] 被删除
  • 扔掉这个,你试过=regex.sub(" ",text)吗?

标签: python list punctuation


【解决方案1】:

我相信你可以在 delta 上调用内置的replace 函数,所以你的最后一行会变成下面这样:

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

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

【讨论】:

    【解决方案2】:

    上述方法可能不起作用,因为您仍会从初始字符串中删除所有破折号(“-”)字符。如果您希望它工作,请将其从列表点中删除。更新后的代码如下所示:

    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 中的所有字符替换为空字符串,并且您希望为“-”留一个空格。因此,您需要将字符替换两次(一次用空字符串,一次用空格)。

    【讨论】:

      猜你喜欢
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2019-08-04
      • 1970-01-01
      • 2016-09-01
      • 2018-06-15
      相关资源
      最近更新 更多