簡體   English   中英

刪除csv文件中的換行符

[英]removing line breaks in a csv file

我有一個帶行的csv文件,每行以(@)開頭,一行中的所有字段都用(;)分隔。 其中一個包含“Text”(“”[]“”)的字段有一些換行符,這些換行符在將整個csv文件導入excel或access時會產生錯誤。 換行后的文本被視為獨立行,而不是遵循表的結構。

@4627289301; Lima, Peru; 490; 835551022915420161; Sat Feb 25 18:04:22 +0000 2017; ""[OJO!
la premiacin de los #Oscar, nuestros amigos de @cinencuentro revisan las categoras.
+info: co/plHcfSIfn8]""; 0
@624974422; None; 114; 835551038581137416; Sat Feb 25 18:04:26 +0000 2017; ""[Porque nunca dejamos de amar]""; 0

使用python腳本的任何幫助? 或任何其他解決方案......

作為輸出我想有線:

@4627289301; Lima, Peru; 490; 835551022915420161; Sat Feb 25 18:04:22 +0000 2017; ""[OJO! la premiacin de los #Oscar, nuestros amigos de @cinencuentro revisan las categoras. +info: co/plHcfSIfn8]""; 0
@624974422; None; 114; 835551038581137416; Sat Feb 25 18:04:26 +0000 2017; ""[Porque nunca dejamos de amar]""; 0

任何幫助? 我是一個csv文件(54MB),有很多行換行...其他一些行也行......

您也應該分享您的預期輸出。

無論如何,我建議你先清理文件以刪除換行符。 然后你可以把它讀作csv。 一個解決方案可以是(我相信有人會提出更好的建議:-))

清理文件(在linux上):

sed ':a;N;$!ba;s/\n/ /g' input_file | sed "s/ @/\n@/g" > output_file

將文件讀取為csv (您可以使用任何其他方法讀取它)

import pandas as pd
df = pd.read_csv('output_file', delimiter=';', header=None)
df.to_csv('your_csv_file_name', index=False)

讓我們看看它是否對你有幫助:-)

您可以搜索后面跟不以“@”開頭的行的行,例如\\r?\\n+(?!@\\d+;)

以下是從此regex101 演示生成的。 它用空格替換這樣的線端。 您可以將其更改為您喜歡的任何內容。

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"\r?\n+(?!@\d+;)"

test_str = ("@4627289301; Lima, Peru; 490; 835551022915420161; Sat Feb 25 18:04:22 +0000 2017; \"\"[OJO!\n"
    "la premiacin de los #Oscar, nuestros amigos de @cinencuentro revisan las categoras.\n"
    "+info: co/plHcfSIfn8]\"\"; 0\n"
    "@624974422; None; 114; 835551038581137416; Sat Feb 25 18:04:26 +0000 2017; \"\"[Porque nunca dejamos de amar]\"\"; 0")

subst = " "

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

暫無
暫無

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

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