簡體   English   中英

如何在不刪除 endrow 換行符的情況下刪除 csv 列中的換行符?

[英]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)

您可以通過多種方式實現這一目標。

  1. 由於您只關心換行符的最后一次出現,您可以在替換字符串的末尾添加一個換行符
    with open ('filepath') as inf, open('filepath', 'w') as outf:
    for line in inf:
        outf.write(line.replace('\n', '') + '\n')
  1. 您可以計算出現的換行符數,並使用replace 方法的 count 參數傳遞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))
  1. 使用 python 的re庫通過提前檢查替換換行符來進行替換,前提是有一個后續的換行符。
    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.

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