2017-02-21 71 views
0

我有一个包含一些换行数据的tsv文件。如何用python解析tsv文件?

111 222 333 "aaa" 
444 555 666 "bb 
b" 

在第三行这里bbb在第二行上一个新行字符,因此它们是一个数据:

第一行的第四个值:

aaa 

第四第二行值:

bb 
b 

如果我使用Ctrl + C和Ctrl + V粘贴到一个excel文件,它运作良好。但如果我想使用python导入文件,如何解析?

我曾尝试:

lines = [line.rstrip() for line in open(file.tsv)] 
for i in range(len(lines)): 
    value = re.split(r'\t', lines[i])) 

但结果并不好:

enter image description here

我想:

enter image description here

+1

不知道你的这个意思:“在这里B上的第三行是BB的换行符” – Bemmu

回答

1

只需使用csv模块。它知道CSV文件中所有可能的角落案例,例如引用字段中的新行。

with open("file.tsv") as fd: 
    rd = csv.reader(fd, delimiter="\t", quotechar='"') 
    for row in rd: 
     print(row) 

能正确输出:

['111', '222', '333', 'aaa'] 
['444', '555', '666', 'bb\nb'] 
+0

谢谢。这是简单和最好的解决方案。 –

0

换行符,当内容中(单元格).tsv /。 csv通常用引号引起来。否则,标准分析可能会将其混淆为下一行的开始。在你的情况下,行

for line in open(file.tsv) 

自动使用换行符作为分隔符。

如果您确定文件只有4列,您可以简单地阅读整个文本,根据选项卡拆分它,然后一次提取4个项目。

# read the entire text and split it based on tab 
old_data = open("file.tsv").read().split('\t') 

# Now group them 4 at a time 
# This simple list comprehension creates a for loop with step size = num. of columns 
# It then creates sublists of size 4 (num. columns) and puts it into the new list 
new_data = [old_data[i:i+4] for i in range(0, len(old_data), 4)] 

理想情况下,您应该关闭可能引用换行符的内容。

+0

非常感谢你。是的,真实的数据是双引号。我编辑了这个话题。我会读你的方法。 –