Python: 搜索和替换 - 字符串描述问题

Python: search and replace - string delineation issue

尝试查找并替换字符串列表(以换行符分隔),例如

aba
abanga
abaptiston
abarelix

列表如

aba
aca
ada

这样,如果第二个列表中的项目出现在第一个列表中,则应将其删除。

我有一半有效的代码

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

with open("words.txt", "r") as f:
    content = f.readlines()

str = ''.join(str(e) for e in content)  #list may include numbers

delet = {"aba":"", "aca":"", "ada":"",}
txt = replace_all(str, delet)

f = open("deltedwords.txt","w") 
f.write(txt)

不幸的是,这会捕获部分字符串的误报,因此最终结果将是

nga
ptiston
relix

尝试在要搜索的词之前添加空格或其他字符是行不通的,因为它往往只会产生漏报。

您可以简单地过滤,但我认为如果您只是删除条目,则不需要字典。

如果顺序无关紧要,请使用 set:

>>> content = set(['aba', 'abanga', 'abaptiston', 'abarelix'])
>>> unwanted_words = set(['aba', 'aca', 'ada'])
>>> content.difference(unwanted_words)
set(['abanga', 'abarelix', 'abaptiston'])

如果是,就使用列表推导

>>> content = ['aba', 'abanga', 'abaptiston', 'abarelix']
>>> unwanted_words = ['aba', 'aca', 'ada']
>>> [word for word in content if word not in unwanted_words]
['abanga', 'abaptiston', 'abarelix']

如何使用:

content_without_keywords = filter(lambda x: x.strip() not in delet.keys(), content)
txt = ''.join(str(e) for e in content_without_keywords)

仅删除完全匹配的行。