一段代码,批量匹配file中的关键词并在正文中将关键词标记, 在这个基础,如何返回未匹配的关键词,同时见这些关键词保存在一个新的txt内?

with open('keyword.txt', 'r') as file:
    keyword = [word.strip() for word in file.readlines()]

with open('file.txt', 'r') as file:
    article = file.read()

for word in keyword:
    article = article.replace(word, f"<b>{word}</b>")

print(article)

一段代码,批量匹配file中的关键词并在正文中将关键词标记,
在这个基础,如何返回未匹配的关键词,同时见这些关键词保存在一个新的txt内?

可以使用列表推导式来找出未匹配的关键词,并将其保存在一个新的txt文件内。以下是修改后的代码:

with open('keyword.txt', 'r') as file:
    keyword = [word.strip() for word in file.readlines()]

with open('file.txt', 'r') as file:
    article = file.read()

unmatched_keywords = []
for word in keyword:
    if word in article:
        article = article.replace(word, f"<b>{word}</b>")
    else:
        unmatched_keywords.append(word)

print(article)

with open('unmatched_keywords.txt', 'w') as file:
    for word in unmatched_keywords:
        file.write(word + '\n')

这段代码将在 unmatched_keywords.txt 文件中保存未匹配到的关键词列表。

望采纳。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7409276
  • 我还给你找了一篇非常好的博客,你可以看看是否有帮助,链接:怎样给txt文件首列添加行号并保存在txt文件
  • 除此之外, 这篇博客: 爬虫爬取小说网站的内容,并将各章节输出到各txt文件中的 二、查看网页源代码 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    发现:
    1、网站是gbk编码的
    在这里插入图片描述
    2、章节都是有a标签的,要过滤出来这部分内容
    3、我们要的是从正文卷开始的章节,想到切片截取
    在这里插入图片描述

    # 获取结果res,编码是gbk(这个网站就是gbk的编码)
    res = requests.get(link)
    res.encoding = 'gbk'
    
    # 使用BeatifulSoup得到网站中的文本内容
    soup = BeautifulSoup(res.text)
    lis = soup.find_all('a')	# 
    lis = lis[42:-13]           # 不属于章节内容的都去掉
    
    # 用urllist存储所有{章节名称:链接}
    urldict = {}
    
    # 观察小说各个章节的网址,结合后面的代码,这里只保留 split_link = 'https://www.biqukan.com/'
    tmp = link.split("/")
    split_link = "{0}//{1}/".format(tmp[0], tmp[2])
    
    # 将各章节名字及链接形成键值对形式,并添加到大字典 urldict中
    for i in range(len(lis)):
        print({lis[i].string: split_link + lis[i].attrs['href']})
        urldict.update({lis[i].string: split_link + lis[i].attrs['href']})
    
    from tqdm import tqdm
    for key in tqdm(urldict.keys()):
        tmplink = urldict[key]          # 章节链接
        res = requests.get(tmplink)     # 链接对应的资源文件html
        res.encoding = 'gbk'
    
        soup = BeautifulSoup(res.text)  # 取资源文件中的文本内容
        content = soup.find_all('div', id='content')[0]  # 取得资源文件中文本内容的小说内容
    
        with open('text{}.txt'.format(key), 'a+', encoding='utf8') as f:
            f.write(content.text.replace('\xa0', ''))
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^