删除csv fi中的换行符

2024-06-26 14:32:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有行的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脚本有什么帮助吗?或者其他解决方案。。。在

作为输出,我希望有以下行:

^{pr2}$

有什么帮助吗?我有一个csv文件(54MB)有很多行和换行。。。其他的线路也可以。。。在


Tags: 文件csvtext文本access错误de结构
2条回答

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

以下是从regex101demo生成的。它用一个空格来代替这些行尾。你可以把它改成你喜欢的任何东西。在

# 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.

你也应该分享你的预期产出。在

不管怎样,我建议你先清理文件以删除换行符。然后你可以把它读作csv。一个解决方案可以是(我相信有人会提出更好的建议:-)

清理文件(在linux上):

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

以csv格式读取文件(可以使用任何其他方法读取)

^{pr2}$

让我们看看它是否对你有帮助:-)

相关问题 更多 >