簡體   English   中英

如何使用 Python 從 txt 文件中刪除特殊字符

[英]How to remove special characters from txt files using 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

到目前為止,我的代碼是這樣的。 這會計算D:\report\shakeall\*.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)

它會將每個非字母數字字符更改為空格。

我很新,我懷疑這根本不是很優雅,但一種選擇是在讀入字符串后取出它們並通過 string.translate() 運行它們以去除標點符號。 這是2.7 版的 Python 文檔(我認為您正在使用)。

就實際代碼而言,它可能是這樣的(但也許比我更好的人可以確認/改進它):

fileString.translate(None, string.punctuation)

其中“fileString”是您的 open(fp) 讀入的字符串。提供“None”代替轉換表(通常用於將某些字符實際更改為其他字符),以及第二個參數 string.punctuation (包含所有標點符號的 Python 字符串常量)是一組將從您的字符串中刪除的字符。

如果上述方法不起作用,您可以修改如下:

inChars = string.punctuation
outChars = ['']*32
tranlateTable = maketrans(inChars, outChars)
fileString.translate(tranlateTable)

我通過快速搜索找到了一些類似問題的其他答案。 我也會把它們鏈接到這里,以防你能從它們那里得到更多。

從 Python 列表項中刪除標點符號

從字符串中刪除所有特殊字符、標點符號和空格

在 Python 2.x 中去除特定標點符號


最后,如果我所說的完全錯誤,請發表評論,我將刪除它,以免其他人嘗試我所說的並感到沮喪。

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()]

這將在將每個單詞添加到集合之前從每個單詞中刪除所有尾隨的非字母數字字符。

在 Linux 工作時,/proc lib 中的某些系統文件包含 ascii 值為 0 的字符。

            full_file_path = 'test.txt'
            result = []
            with open(full_file_path, encoding='utf-8') as f:

                line = f.readline()
                for c in line:
                    if ord(c) == 0:
                        result.append(' ')
                    else:
                        result.append(c)
            print (''.join(result))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM