【发布时间】:2014-04-22 19:49:44
【问题描述】:
我想解析一个 csv 文件,格式如下:
Test Environment INFO for 1 line.
Test,TestName1,
TestAttribute1-1,TestAttribute1-2,TestAttribute1-3
TestAttributeValue1-1,TestAttributeValue1-2,TestAttributeValue1-3
Test,TestName2,
TestAttribute2-1,TestAttribute2-2,TestAttribute2-3
TestAttributeValue2-1,TestAttributeValue2-2,TestAttributeValue2-3
Test,TestName3,
TestAttribute3-1,TestAttribute3-2,TestAttribute3-3
TestAttributeValue3-1,TestAttributeValue3-2,TestAttributeValue3-3
Test,TestName4,
TestAttribute4-1,TestAttribute4-2,TestAttribute4-3
TestAttributeValue4-1-1,TestAttributeValue4-1-2,TestAttributeValue4-1-3
TestAttributeValue4-2-1,TestAttributeValue4-2-2,TestAttributeValue4-2-3
TestAttributeValue4-3-1,TestAttributeValue4-3-2,TestAttributeValue4-3-3
并希望将其转换为制表符分隔格式,如下所示:
TestName1
TestAttribute1-1 TestAttributeValue1-1
TestAttribute1-2 TestAttributeValue1-2
TestAttribute1-3 TestAttributeValue1-3
TestName2
TestAttribute2-1 TestAttributeValue2-1
TestAttribute2-2 TestAttributeValue2-2
TestAttribute2-3 TestAttributeValue2-3
TestName3
TestAttribute3-1 TestAttributeValue3-1
TestAttribute3-2 TestAttributeValue3-2
TestAttribute3-3 TestAttributeValue3-3
TestName4
TestAttribute4-1 TestAttributeValue4-1-1 TestAttributeValue4-2-1 TestAttributeValue4-3-1
TestAttribute4-2 TestAttributeValue4-1-2 TestAttributeValue4-2-2 TestAttributeValue4-3-2
TestAttribute4-3 TestAttributeValue4-1-3 TestAttributeValue4-2-3 TestAttributeValue4-3-3
TestAttributes 的数量因测试而异。对于某些测试,只有 3 个值,而对于其他一些测试,则为 7 个,等等。同样如在 TestName4 示例中,一些测试执行了不止一次,因此每次执行都有自己的 TestAttributeValue 行。 (在示例中 testname4 执行了 3 次,因此我们有 3 个值行)
我是python新手,知识不多,但想用python解析csv文件。我检查了 python 的 'csv' 库,不确定它对我来说是否足够,还是我应该编写自己的字符串解析器?你能帮帮我吗?
最好的
【问题讨论】:
-
您真的尝试过
csv模块吗?它奏效了吗?如果没有,什么没有起作用? -
使用csv.reader 并将参数
delimiter设置为","将允许您以字符串列表的形式检索文件的内容。从那里你需要重新格式化整个结构。 -
@LutzHorn 实际上我无法详细查看 csv 模块,我希望我能在几个小时内有时间。但是,只要我理解,在我的情况下,仅用中间的“,”分隔文本才有用。所以我想那个 csv 模块有什么用?我可以通过编写一个简单的文本解析器来检查“,”是否存在。我很好奇 csv 模块是否比仅查找“,”并为我的案例分隔值更有用。我不知道我是否在寻找魔法:)
-
CSV 也可以命名为 DSV:分隔符分隔值。分隔符也可以是空格。您应该 1) 找到一种方法将输入拆分为块,以及 2) 将这些块解析为 CSV。