[英]Python - split on tab and create a new line
I am new to python. 我是python的新手。 I have raw data that is split into '\\t' and \\n'
我有原始数据,分为“ \\ t”和“ \\ n”
Sample data: 样本数据:
Apple Fruit
Orange Fruit
Car Vehicle
Truck Vehicle
Output should look like with '\\n' in between: 输出看起来应该像介于“ \\ n”之间:
Apple
Fruit
Orange
Fruit
Car
Vehicle
Truck
Vehicle
Here is what I tried: 这是我尝试过的:
filename = open('data/att.txt','r')
rdata = filename.read()
print(rdata)
{line.strip().split('\t')[0]:line.split('\t')[1] for line in rdata.splitlines() if line.strip() = '\n'}
I keep getting invalid syntax error. 我不断收到无效的语法错误。 How do I fix this?
我该如何解决? Thanks!
谢谢!
Consider this: 考虑一下:
{line.strip().split('\t')[0]:line.split('\t')[1] for line in rdata.splitlines() if line.strip() == '\n'}
Use "==" to test for equality and "=" to set value to the variable. 使用“ ==”测试是否相等,使用“ =”将值设置为变量。
I think this code might help you to avoid the error that was the "=" instead of "==" and also help you to convert it into a more readable code. 我认为这段代码可以帮助您避免出现“ =”而不是“ ==“的错误,并且还可以帮助您将其转换为可读性更高的代码。
file = open('data/att.txt','r')
for line in file :
aux = line.strip().split('\t')
print(aux[0])
print(aux[1], end='\n\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.