从文件中删除单词(如果存在于另一个文件中)



我有 2 个字符串文件。

两个文件中的某些字符串是相同的。

我想删除这些字符串并将其写入新文件。

这是我的源代码:

file = open ("fileC.txt", "w")
with open('fileA.txt') as a, open('fileB.txt') as b:
    a_words = set(a.read().split())
    b_words = set(b.read().split())
    both_words = ('n'.join(a_words & b_words))
    c_words = a_words.replace(both_words, "")
    print (c_words)
    file.write(c_words + "n)
file.close()

这将产生以下错误:

AttributeError: 'set' object has no attribute 'replace'

我也尝试了列表,而不是集合:

a_words = a.read().split()
b_words = b.read().split()
c_words = a_words.replace(b_words, "")

这会产生此错误:

AttributeError: 'list' object has no attribute 'replace'

你能帮忙吗?

file = open ("fileC.txt", "w")
with open('fileA.txt') as a, open('fileB.txt') as b:
    b=b.read().split()
    r='n'.join([e for e in a.read().split() if e not in b])
    file.write(r)

试试这个

相关内容

最新更新