【问题标题】:Strip in Python until the last same blank char and remove a char in the end of the line在 Python 中剥离直到最后一个相同的空白字符并在行尾删除一个字符
【发布时间】:2016-10-31 00:30:51
【问题描述】:

我有这样的输入(数百万行)

1   /home/ubuntu/test_images/test0.png      output  [ 0.03921137 0.00651542]
2   /home/ubuntu/test_images/test1.png      output  [ 0.03896755 0.00643029]
3   /home/ubuntu/test_images/test2.png      output  [ 0.03919738 0.00645864]
4   /home/ubuntu/test_images/test3.png      output  [ 0.0392952 0.00693588]
...

想要这个输出

0.00651542
0.00643029
0.00645864
0.00693588
...

需要删除直到最后一个空格并删除“\n”之前的“]”,但我失败了。有什么建议么?谢谢你。

【问题讨论】:

  • 按空格分割,取最后一列,去掉右括号?

标签: python string split strip


【解决方案1】:

基本上,您想使用.rstrip() 删除行尾的\n,将输入拆分为空格,获取最后一个元素(例如0.0000]),然后切片以删除尾随的]。

with open('test_txt.txt') as f:
    for line in f:
        print(line.rstrip().split(" ")[-1][:-1])

【讨论】:

    【解决方案2】:

    这可以通过拆分、索引和切片来解决:

    >>> x = '1   /home/ubuntu/test_images/test0.png      output  [ 0.03921137 0.00651542]'
    >>> x.split()[-1][:-1]
    '0.00651542'
    

    根据需要对每一行重复。

    以下是修改后的程序:

    >>> def p(s):
    ...     x = s.split()
    ...     if x[-1] == ']': return x[-2]
    ...     return x[-1][:-1]
    ... 
    >>> p('1   /home/ubuntu/test_images/test0.png      output  [ 0.03921137 0.00651542]')
    '0.00651542'
    >>> p('1   /home/ubuntu/test_images/test0.png      output  [ 0.03921137 0.00651542 ]')
    '0.00651542'
    

    第二个字符串以' ]'结尾。

    【讨论】:

    • 有一个新问题 =/ 有些行在“]”之前多了 1 个空格,例如:“output [0.03811574 0.841492]”。这打破了我的愿望清单...
    【解决方案3】:

    rsplit 可能会更有效一些。这样您就不会在每次迭代的每个拆分列表中创建尽可能多的元素。

    例如

    Python 3

    with open('f.txt') as f:
        for line in f:
            rest, end = line.rsplit(maxsplit=1)
            print(end[:-1])
    

    输出:

    0.00651542
    0.00643029
    0.00645864
    0.00693588
    

    对于 Python 2,可以这样做

    with open('f.txt') as f:
        for line in f:
            rest, end = line.rsplit(None, 1)
            print(end[:-1])
    

    【讨论】:

    • 谢谢,但我得到了:TypeError: rsplit() 没有关键字参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    相关资源
    最近更新 更多