我想匯入一個文本檔案,它有 14 列,帶有符號“;” 作為列分隔符。所以,如果我們有 14 列,這意味著我們會找到 13 個“;” 每行/行中的分隔符。
問題是,正如您在下面看到的,有一行,帶有“;” 其中一列中的字符。
它使這條線有 14 個“;” 分隔符(轉換為 15 列)。

如果我們在 Excel 中打開檔案,我們可以在那里看到這個錯誤的“額外”列:

嘗試使用“read_csv”pandas函式讀取此檔案時,會引發錯誤,提示您有 15 列(而不是 14 列)。

因此,在使用 read_csv 函式之前,我想打開檔案,找到帶有 14 ";" 的行 行中的分隔符,修改/替換“;”的第 13 次出現 帶有“.”的符號 并寫回另一個文本檔案。
由于字串在 Python 中是不可變的,理論上,我不知道如何繼續我的 Python 腳本。懷疑解決方案是附加在串列中還是粘貼文本。順便說一句,這段代碼將成為最終腳本的一部分,因為這個問題將來會發生更多次。
# Creating an empty list to store all the lines from the file will be readed.
listoflines = []
# Opening the file.txt in only "reading" model
with open(r"D:\file.txt", mode='r') as reader:
for line in reader.readlines():
listoflines.append(line)
# Creating an empty list to store all the lines including the modified lines.
finaldocument = []
# Detecting the row(s) where the count of the ";" symbol is equal to 14.
for row in listoflines:
if row.count(';') == 14:
# Creating a counter.
n=0
# Iterating over the letters of the row
for letter in row:
if letter == ';':
n =1
# We need to detect the 13rd ";" symbol of the row.
if n==13:
print(letter)
letter = letter.replace(';','.')
print(letter)
## HOW TO APPEND/REPLACE THE MODIFIED LETTER TO THE ROW???? ##
# Storing, again, all the lines (including modified lines) to a final object.
finaldocument.append(row)
print(finaldocument)
uj5u.com熱心網友回復:
您不應將該分號替換為另一個字符,而應將字串用雙引號括起來(并通過將它們加倍來轉義可能已經是字串一部分的任何雙引號)。這就是在 CSV 語法中包含此類分隔符的方式。事實上,總是用雙引號括起這樣的文本并不是一個壞習慣。
這是我如何調整你的回圈:
for row in listoflines:
if row.count(';') > 13: # maybe there are even two or more of them
cells = row.split(';')
# Escape double quotes and wrap in double quotes
s = '"' ';'.join(cells[12:-1]).replace('"', '""') '"'
# Replace the involved parts with that single part
cells[12:-1] = [s]
# ...and convert back to the string format
row = ';'.join(cells)
finaldocument.append(row)
uj5u.com熱心網友回復:
而不是這樣做:
if row.count(';') == 14:
# Creating a counter.
n=0
# Iterating over the letters of the row
for letter in row:
if letter == ';':
n =1
# We need to detect the 13rd ";" symbol of the row.
if n==13:
print(letter)
letter = letter.replace(';','.')
print(letter)
這樣做:row = row.split(";")這會將行轉換為串列,如果你只需要 len 14 你可以添加這個:row = row[:14]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470725.html
