[英]How to remove newline characters in csv columns, without removing the endrow newline character?
所以我有這個數據集,其中有時會在某些單元格中輸入隨機換行符,我需要刪除它們。
這是我試過的:
with open ('filepath') as inf, open('filepath', 'w') as outf:
for line in inf:
outf.write(line.replace('\n', ''))
不幸的是,這刪除了所有換行符,包括行尾的換行符,這將我的 csv 文件變成了一個大的單行
有誰知道我怎么只能刪除隨機換行符而不是“真正的”結尾字符?
編輯:如果有幫助,每個“真正的”新行都以 6 位數字字符串開頭(除了 header 行)。 也許一些正則表達式模式可以提前檢測是否有一些數字字符串可以工作?
Edit2:我試過使用 pandas 來編輯它:
df = pd.read_csv(filepath)
for i in df.columns:
if df[i].dtype==np.object:
df[i] = df[i].str.replace('\n','')
奇怪的是,如果我將 .csv 中的內容復制到一個新的文本文件中,這會起作用,但它不適用於我原來的 csv 文件,我不確定為什么。
最終編輯:
非常感謝 DDS 的幫助。 設法讓它工作使用這個:
num_cols = 48
buf = ""
with open (filepath) as inf, open (filepath, 'w') as outf:
for line in inf:
if len(line.split(',')) < num_cols:
buf += line.replace('\n', '')
if len(buf.split(',')) == num_cols:
outf.write(buf+'\n')
else: continue
buf = ""
else:
outf.write(line)
您可以通過多種方式實現這一目標。
with open ('filepath') as inf, open('filepath', 'w') as outf:
for line in inf:
outf.write(line.replace('\n', '') + '\n')
n - 1
作為要替換的換行符數 with open ('filepath') as inf, open('filepath', 'w') as outf:
for line in inf:
outf.write(line.replace('\n', '', line.count('\n') - 1))
import re
result = re.sub( '\n*(?=.*\n)','' ,'ansd\nasdn\naskd\n')
print(result)
'ansdasdnaskd\n'
首先控制你的行是否為空而不是寫行
for line in inf:
if len(line.strip()) == 0:
outf.write(line.replace('\n', ''))
else:
outf.write(line)
假設您知道每行的字段數並且沒有字段包含 csv 分隔符(逗號):您可以這樣做:
number_of_columns_in_the_table = 5 #assuming a line has 5 columns
with open ('filepath') as inf, open('filepath', 'w') as outf:
for line in inf:
#check if the number of "splits equals the nummber of fields"
if len(line.split(',')) < number_of_columns_in_the_table
outf.write(line.replace('\n', ''))
else:
outf.write(line)
編輯
number_of_columns_in_the_table = 5 #assuming a line has 5 columns
with open ('filepath') as inf, open('filepath', 'w') as outf:
for line in inf:
#check if the number of "splits equals the nummber of fields"
if len(line.split(',')) < number_of_columns_in_the_table
buf += line.replace('\n', '');
if len(line.split(',')) == number_of_columns_in_the_table
outf.write( buf)
else:
outf.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.