如何使用Python从txt文件中删除特殊字符

roc*_*and 4 python

from glob import glob
pattern = "D:\\report\\shakeall\\*.txt"
filelist = glob(pattern)
def countwords(fp):
    with open(fp) as fh:
        return len(fh.read().split())
print "There are" ,sum(map(countwords, filelist)), "words in the files. " "From directory",pattern
import os
uniquewords = set([])
for root, dirs, files in os.walk("D:\\report\\shakeall"):
    for name in files:
        [uniquewords.add(x) for x in open(os.path.join(root,name)).read().split()]
print "There are" ,len(uniquewords), "unique words in the files." "From directory", pattern
Run Code Online (Sandbox Code Playgroud)

到目前为止我的代码是这样的.这会计算来自的唯一单词和总单词的数量D:\report\shakeall\*.txt

问题是,例如,此代码识别code code.code!不同的单词.因此,这不能解决确切数量的独特单词.

我想使用Windows文本编辑器从42个文本文件中删除特殊字符

或者制定解决此问题的例外规则.

如果使用后者,我的代码怎么样?

让它直接修改文本文件?或者做一个不计算特殊字符的异常?

NIl*_*rma 9

import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)
Run Code Online (Sandbox Code Playgroud)

它会将每个非字母数字字符更改为空格.