【问题标题】:Python - Separating by tabs and new linesPython - 按制表符和新行分隔
【发布时间】:2017-01-30 22:15:53
【问题描述】:

我正在尝试用 Python 读取一个看起来像这样的文件:

hello\t\tsecondhello\n
this\t\tsecondthis\n
is\t\tsecondis\n
data\t\tseconddata\n

我只对每行的第二条信息感兴趣,所以我试图摆脱这两个标签和新行。我试过这个:

documents = open("data.txt", "r").readlines()
for line in documents:
    splitted = line.strip().split("\t")
    print(splitted) 

但这只会给我列出如下所示的对象:

['hello\t\tsecondhello']

我也看过这个接受的答案,但它给我的只是新行也被保留:splitting a string based on tab in the file

编辑:发现错误,它是输入文件中的错误格式。仍然,感谢您的帮助,人们

【问题讨论】:

  • line.strip().split("\t\t")?
  • 不,已经试过了,得到完全相同的输出
  • 我没有得到相同的结果。我使用的是 Python 2.7,并且我将每一行分成三个字段,正如我所期望的那样:['hello'、''、'secondhello'] 等行。您可以尝试一次打印一个字符的行和拆分字符串吗?
  • 我正在使用 python 3.5 和 .split("\t\t") 将完成工作,.split("\t") 给出与 Prune 提到的相同的结果。
  • splitted = line.strip().split("\t")[2] 给出第二个值

标签: python split


【解决方案1】:

看起来你的 \t 实际上是转义的,而不是实际的标签。所以试试

line.strip().split("\\t\\t")

【讨论】:

  • 很遗憾,我得到了同样的结果
【解决方案2】:

这适用于您提供的数据:

data = documents.strip().split('\n')
wanted_data = [item.split('\t')[2] for item in data if item]

【讨论】:

  • 得到这个AttributeError: 'list' object has no attribute 'strip'
  • 如果我的回答有帮助,别忘了accept。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2011-03-06
  • 2011-06-09
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2018-07-10
  • 2012-10-10
相关资源
最近更新 更多