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

标签 python list punctuation

我正在尝试从文本文件中删除标点符号列表,但只有一个与连字符分隔的单词问题。例如,如果我有“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 )

有办法解决吗?

最佳答案

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

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

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

关于Python从文本文件中删除标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41225435/

相关文章:

c++ - C++ 中的小数点 ('.' 是多少,我可以做一个吗?

python - pandas 数据框列的最大数量相乘

python - 如何计算作为字符串列表的 Pandas 列中的值?

python - 理解 One Line For 循环

python - 创建 for 循环直到 list.length

android - 参数 ITEMS 的非法修饰符;只允许 final

regex - 删除标点符号,但不是全部

python - 在 python xmlrpc 代理上使用 getattr

python - 寻找一种解决方案来检测带有列表的类属性中的值更改并追加

mysql - MySQL如何处理无效字符