【问题标题】:Remove duplicate lines from a string in python从python中的字符串中删除重复的行
【发布时间】:2015-02-14 17:42:10
【问题描述】:

我在 python 中有一个字符串,并且想删除重复的行(即当 \n 之间的文本相同时,然后删除第二(第三,第四)次出现,但保留字符串的顺序。例如

line1 \n line2 \n line3 \n line2 \n line2 \n line 4

会返回:

line1 \n line2 \n line3 \n line 4

我在 stackoverflow 上看到的其他示例处理在将文本文件读入 python 的阶段(例如,使用 readline(),查看是否已经在一组读入行中,然后仅当它是唯一的时才添加到字符串)。在我的例子中,这是行不通的,因为自从加载到 python 之后,我已经对字符串进行了大量操作......而且它看起来很糟糕,例如将整个字符串写入 txt 文件,然后逐行读取以查找重复行

【问题讨论】:

  • 你试过什么?我认为这并不难。对于初学者来说,只需拆分这个字符串,然后在另一个循环中,开始添加唯一值。
  • 每行的开头是否总是有一个空格?

标签: python regex python-2.7


【解决方案1】:

对于 Python 2.7+,这可以通过单行来完成:

from collections import OrderedDict

test_string = "line1 \n line2 \n line3 \n line2 \n line2 \n line 4"

"\n".join(list(OrderedDict.fromkeys(test_string.split("\n"))))

这给了我:'line1 \n line2 \n line3 \n line 4'

【讨论】:

    【解决方案2】:
    >>> lines = "line1 \n line2 \n line3 \n line2 \n line2 \n line 4"
    >>> seen = set()
    >>> answer = []
    >>> for line in lines.splitlines():
    ...     if line not in seen:
    ...             seen.add(line)
    ...             answer.append(line)
    ... 
    >>> print '\n'.join(answer)
    line1 
     line2 
     line3 
     line 4
    >>> '\n'.join(answer)
    'line1 \n line2 \n line3 \n line 4'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      • 2018-09-16
      • 2017-04-03
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 2018-08-27
      相关资源
      最近更新 更多