我正在嘗試將位于不同文件夾中的多個文本文件讀取到一個文件中,并針對奇怪的格式問題進行調整,尤其是讀取時的特殊字符。我的輸入文件如下所示:cat date col1 col2 col3x 3/1/2010 " 823,312,356 "" 145,019,711 "" "" 666,666 "" " x 3/8/2010 " 3,423,115,838 "" 111,422,457 "" "" 311,512 "" " x 3/15/2010 " 4,117,664,854 ""115,115,141 "" "" 213,550 """ x 3/22/2010 527,337,127 " "" 153,423,891 "" "" 216,365 "" " x 3/29/2010 "459,227,151" " "" 57,213,333 "" 454,718 x 4/6/2010 "367,221,146" " "" 72,458,231 """ "264,130"x 4/13/2010 - - $0我需要解決很多奇怪的格式問題。我正在嘗試這個:import globread_files = glob.glob(data_path + "*.txt")with open(data_path +"final.txt", "wb") as outfile: for f in read_files: with open(f, "rb") as infile: infile = re.sub(r"[-()\"#@;:<>{}`+=~|.!?,]", "", infile) outfile.write(infile.read())但我收到一條錯誤消息,內容如下:類型錯誤:預期的字符串或類似字節的對象有人遇到過同樣的問題嗎?
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
with open(f, "rb") as infile:
infile = re.sub(r"[-()\"#@;:<>{}`+=~|.!?,]", "", infile)
outfile.write(infile.read())
首先,打開文件時使用'b'將文件內容視為bytes對象,而不是字符串(類型str)。這不適用于作為字符串給出的正則表達式模式。所以你應該忽略'b'. 由于其余的'r'是打開文件的默認模式,因此您可以完全省略第二個參數open()。
接下來,您將文件對象與文件內容混淆,并且操作順序錯誤。
infile.read()讀取文件的內容并將其作為字符串返回(當省略 時'b')。該字符串可以傳遞給re.sub.
所以正確的順序是:
with open(f) as infile:
text = infile.read()
replaced_text = re.sub(r"[-()\"#@;:<>{}`+=~|.!?,]", "", text)
outfile.write(replaced_text)
添加回答
舉報
0/150
提交
取消