【问题标题】:how to delete words which are same in two files?如何删除两个文件中相同的单词?
【发布时间】:2012-06-23 18:33:33
【问题描述】:

我有两个文本文件。

file1.txt 有:

gedit
google chrome
git
vim
foo
bar

file2.txt 有:

firefox
svn
foo
vim

我如何编写一个脚本,在执行时(以 file1.txt 和 file2.txt 作为参数)检查每一行(我的意思是它应该逐行处理),删除两个文件中的重复文本。

所以经过处理后,file1.txt和file2.txt都应该有如下内容:

gedit
google chrome
git
bar
firefox
svn

请注意,foo 和 vim 已从这两个文件中删除。

有什么指导吗?

【问题讨论】:

  • 为什么有两个文件内容相同?这些文件有多大,它们同时打开时是否可以放入内存? + what have you tried 到目前为止?
  • 尝试使用 set() 数据结构来查找重复项。 docs.python.org/library/sets.html
  • @deathApril 假设我正在重新安装我的 Ubuntu。所以我通过dpkg --get-selection 命令(file1.txt)得到了一个包列表,我自己制作了另一个列表(file2.txt),这个文件包含我记得我安装的内容。重新安装 Ubuntu 后,我通过查看 file2.txt 安装了软件。现在需要安装这两个文件的剩余内容。现在剩下的部分在我的问题中......
  • 始终尝试为每个单独的任务考虑正确的数据类型。如果成功了,你的路就顺利了。最简单的方法是寻找能够满足您的需求(以及内部函数的需求)的现有数据类型:最少的麻烦,最好的效率。
  • 内容的顺序重要吗?

标签: python python-2.7


【解决方案1】:
with open('file1.txt','r+') as f1 ,open('file2.txt','r+') as f2:
    file1=set(x.strip() for x in f1 if x.strip())
    file2=set(x.strip() for x in f2 if x.strip())
    newfile=file1.symmetric_difference(file2) #symmetric difference removes those values which are present in both sets, and returns a new set.
    f2.truncate(0) #truncate the file to 0 bytes
    f1.truncate(0)
    f2.seek(0) # to push the cursor back to the starting pointing in the file.
    f1.seek(0)
    for x in newfile:
        f1.write(x+'\n')
        f2.write(x+'\n')

现在两个文件都包含:

svn
git
firefox
gedit
google chrome
bar

【讨论】:

  • +1 与对称差异的良好接触 (file1 ^ file2)
  • set() 是做什么的?
  • @SantoshKumar set 从可迭代/迭代器返回唯一项。
【解决方案2】:

您会将过滤后的文件另存为第三个文件吗?

无论如何,对每个文件进行 2 次循环,并将每个循环索引值与另一个进行比较,如果它们相等,则删除并相应地移动。伪代码:

Def func(File a, File b):
 for i in a: 
    for j in b:
      if a[i]==b[j]:
        copy and move
      endif
     endfor
  endfor

【讨论】:

  • 不,我希望从两个文件中删除重复项(在两个文件中进行修改)。
【解决方案3】:

如果我正确理解您的问题,应该很容易。

alist = []
for i in ifile1:
    alist.append(i)

for i in ifile2:
    if i in alist:
        alist.remove(i)
    else:
        alist.append(i)

for i in alist:
    print i

【讨论】:

  • 如果您有大量数据,set 将是更好的方法。
【解决方案4】:

如果文件足够小以适合内存,这将完成这项工作:

with open("file1.txt", "r") as f1, open("file2.txt", "r") as f2:
    # create a set from the bigger file 
    result = set(x.strip() for x in f1.readlines())
    # remove duplicates or add unique values from 2nd file
    for line in f2:
        line = line.strip()
        if line in result:
            result.remove(line)
        else:
            result.add(line)
result = "\n".join(result)

# for debug, don't replace original files
with open("file1_out.txt", "w") as f1, open("file2_out.txt", "w") as f2:
    f1.write(result)
    f2.write(result)

# if not inside a function, free memory explicitly  
del result 

【讨论】:

    【解决方案5】:

    对于引入 Counter 的 Python 2.7+

    >>> from collections import Counter
    >>> file_1 = ['gedit','google chrome','git','vim','foo','bar']
    >>> file_2 = ['firefox','svn','foo','vim']
    >>> de_dup = [i for i,c in Counter(file_1+file_2).itertimes() if c == 1]
    >>> de_dup
    ['svn', 'git', 'bar', 'gedit', 'google chrome', 'firefox']
    

    【讨论】:

      【解决方案6】:

      让我们从输入文件名开始:

      files = ('raz.txt','dwa.txt')
      

      还有一些辅助函数。这是一个从文件中读取所有单词的生成器,

      def read(filename):
          with open(filename) as f:
              for line in f:
                  if len(line)>0:
                      yield line.strip()
      

      这会将序列写入文件。

      def write(filename, lines):
          with open(filename, 'w') as f:
              f.write('\n'.join(lines))
      

      让我们创建两个生成器 - 每个输入文件一个

      words = [read(filename) for filename in files]
      

      然后,让我们将生成器列表转换为集合列表

      wordSets = map(set, words)
      

      现在我们有 2 个集合的列表,其中仅包含每个文件中的唯一单词。

      让我们创建另一个集合,其中包含所有输入文件中存在的单词,方法是将它们的集合相交:

      commonWords = set.intersection(*wordSets)
      

      还有改写的时间。

      for filename in files:
      

      由于我们想保存到完全相同的文件,不幸的是,我们需要先将其全部内容读入内存,然后再从那里写入。 (如果您希望在不同的文件中输出,则不必缓冲文件。

      让我们创建一个阅读器生成器,然后通过用list() 包装它来将其全部读取到内存中:

          lines = list(read(filename))
      

      然后将单词按顺序写回给定文件,但前提是它们不在 commonWords 中

          write(filename, (word for word in lines if word not in commonWords))
      

      输入:

      raz.txt

      gedit
      google chrome
      git
      vim
      foo
      bar
      

      dwa.txt

      firefox
      svn
      foo
      vim
      

      输出:

      raz.txt

      gedit
      google chrome
      git
      bar
      

      dwa.txt

      firefox
      svn
      

      从两者中删除了重复项。

      【讨论】:

      • 抱歉 -1,但我发现这篇文章无法阅读 - # comments might help
      猜你喜欢
      • 2017-02-09
      • 2021-11-30
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多