python - 如何删除两个文件中相同的单词?

标签 python python-2.7

我有两个文本文件。

file1.txt 具有:

gedit
google chrome
git
vim
foo
bar

file2.txt 具有:

firefox
svn
foo
vim

如何编写一个脚本,在执行时(使用file1.txtfile2.txt作为参数)检查每行<中的文本重复/strong> (我的意思是它应该按行处理),删除两个文件中的重复文本。

因此处理后,file1.txtfile2.txt都应具有以下内容:

gedit
google chrome
git
bar
firefox
svn

请注意,foovim 已从这两个文件中删除。

有什么指导吗?

最佳答案

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

关于python - 如何删除两个文件中相同的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168517/

相关文章:

python - 通过网络发送加密消息时的 Cryptography.fernet.InvalidToken

python - 在 OSX 10.8.2 上使用 Python 2.7 获取适用于 Google App Engine 的 AppTrace

Python:如何使用 OpenCV 在单击时从网络摄像头捕获图像

python - 仅保留两列 pandas 中不包含值的行

Python 运行 Unittest 作为包导入错误

python-2.7 - 动态上下文无关语法NLTK

python - conda 和 pip 根本不工作

python - 无法通过调用函数使用Xlsxwriter绘制多个图表

python - 为什么 Python 看不到文件中的所有行?

python - 四舍五入到小数点