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

新手上路,请多包涵
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

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

问题是,例如,此代码识别 code code.code! 不同的单词。因此,这不能回答确切数量的唯一单词。

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

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

如果使用后者,我应该如何编写代码?

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

原文由 rocksland 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 381
1 个回答
import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)

它会将每个非字母数字字符更改为空白。

原文由 NIlesh Sharma 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题