如何使用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
如何使用Python从txt文件中删除特殊字符
的问题,例如,该代码识别code
code.
和code!
不同字的数量。所以,这不可能是一个确切数量的独特单词的答案。
我想从使用Windows的文本编辑器
42个文本文件中删除特殊字符或作出这样的解决这一问题的例外规则。
如果使用后者,我该如何编写我的代码?
让它直接修改文本文件?或者做一个不包括特殊字符的例外?
import re
string = open('a.txt').read()
new_str = re.sub('[^a-zA-Z0-9\n\.]', ' ', string)
open('b.txt', 'w').write(new_str)
它会将每个非字母数字字符更改为空格。
你不应该使用'str'作为变量的名字,因为它是一个内置的类。 – Lanaru 2012-08-10 18:12:43
像魔法一样工作:) – 2016-09-17 08:10:26
import re
然后更换
[uniquewords.add(x) for x in open(os.path.join(root,name)).read().split()]
通过
[uniquewords.add(re.sub('[^a-zA-Z0-9]*$', '', x) for x in open(os.path.join(root,name)).read().split()]
此将其添加到集合之前将去除来自每个字中的所有尾随的非字母数字字符。
我很新,我怀疑这是非常优雅的,但有一种选择是在读取字符串并通过string.translate()去除标点符号后运行它们。版本2.7(我认为你正在使用)的Here is the Python documentation for it。
至于实际的代码,它可能是这样的(但也许有人比我更可确认/改进就可以了):
fileString.translate(None, string.punctuation)
其中“fileString”是字符串,你开( fp)读入。“None”代替翻译表(通常用于将某些字符实际更改为其他字符)以及第二个参数string.punctuation(一个包含所有标点符号的Python字符串常量)是一组将从您的字符串中删除的字符。
在这上面不工作的情况下,可以按如下修改:
inChars = string.punctuation
outChars = ['']*32
tranlateTable = maketrans(inChars, outChars)
fileString.translate(tranlateTable)
有几个其他答案我通过快速搜索发现了类似的问题的。我也会在这里把他们联系起来,以防你从他们那里得到更多。
Removing Punctuation From Python List Items
Remove all special characters, punctuation and spaces from string
Strip Specific Punctuation in Python 2.x
最后,如果我说的话是完全错误的,请评论,我会删除它,让其他人不要尝试我已经说了,并感到沮丧。
[如何在SO上格式化代码](http://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks) – Levon 2012-08-10 12:51:29
你可以做set()而不是set([]) – Lanaru 2012-08-10 12:58:32