【问题标题】:How to remove repetitive entries in files如何删除文件中的重复条目
【发布时间】:2015-03-12 08:57:26
【问题描述】:

我有一个文件(input.txt),其中包含以下行:

1_306500682 2_315577060 3_315161284 22_315577259 22_315576763 

2_315578866 2_315579020 3_315163106 1_306500983 

2_315579517 3_315162181 1_306502338 2_315578919 

1_306500655 2_315579567 3_315161256 3_315161708 

由此,我只想保留每行中的第一个条目,在_之前具有重复值。对于上面的例子,output.txt 应该包含:

1_306500682 2_315577060 3_315161284 22_315577259 

2_315578866 3_315163106 1_306500983 

2_315579517 3_315162181 1_306502338 

1_306500655 2_315579567 3_315161256 

请帮忙..

【问题讨论】:

  • StackOverflow 是一个网站,您可以在其中发布有关您遇到的问题的问题,而不是期望其他人完成您的工作的要求列表。那么您是否尝试过自己解决这个问题并遇到问题?你得到了什么错误?你能显示一些代码吗?
  • 是的,这就是你想做的,这就是它应该的样子

标签: python perl file


【解决方案1】:

命令行中的 Perl,

perl -lane 'my %s;print join " ", grep /^(\d+)_/ && !$s{$1}++, @F' file

输出

1_306500682 2_315577060 3_315161284 22_315577259

2_315578866 3_315163106 1_306500983

2_315579517 3_315162181 1_306502338

1_306500655 2_315579567 3_315161256

【讨论】:

    【解决方案2】:
    with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
        for line in infile:
            seen = set()
            nums = line.split()
            for num in nums:
                header = num.split("_")[0]
                if header not in seen:
                    outfile.write(num)
                    outfile.write(" ")
                seen.add(header)
            outfile.write('\n')
    

    【讨论】:

      【解决方案3】:

      您可以使用单独的set 来跟踪到目前为止遇到的单词前缀,并将每行中不重复的前缀收集到list 中。以这种方式处理每一行之后,可以很容易地构造一个替换文本行,其中只包含找到的非重复条目。注意:这只是inspectorG4dget当前答案的一个稍微高效的版本。

      with open('input.txt', 'rt') as infile, \
           open('non_repetitive_input.txt', 'wt') as outfile:
          for line in infile:
              values, prefixes = [], set()
              for word, prefix in ((entry, entry.partition('_')[0])
                                      for entry in line.split()):
                  if prefix not in prefixes:
                      values.append(word)
                      prefixes.add(prefix)
              outfile.write(' '.join(values) + '\n')
      

      输出文件内容:

      1_306500682 2_315577060 3_315161284 22_315577259
      2_315578866 3_315163106 1_306500983
      2_315579517 3_315162181 1_306502338
      1_306500655 2_315579567 3_315161256
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-17
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 1970-01-01
        • 2016-10-27
        • 2022-01-22
        • 1970-01-01
        相关资源
        最近更新 更多