目前 sentences 是按照 keywords 的顺序排列的 ,如何修改代码,使得 sentences 是按照出现在文章中的顺序排列?

一段代码,要求 keywords 匹配 file,生成关键字所在的句子 sentences (关键词只匹配一次),
目前 sentences 是按照 keywords 的顺序排列的 ,如何修改代码,使得 sentences 是按照出现在文章中的顺序排列?


import re

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

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

unmatched_keywords = []
matched_sentences = []
matched_keywords = []

for word in keyword:
# 将正则表达式编译成一个Pattern规则对象
    pattern = re.compile(fr'\b{re.escape(word)}\b')
# 匹配整个字符串,并返回第一个成功的匹配
    match = re.search(pattern, article)
    if match:
        article = re.sub(pattern, f"<b>{match.group()}<b>", article, count=1)
        sentence_pattern = r'[^.!?]*' + re.escape(word) + r'[^.!?]*[.!?]'
        matched_keywords.append(word)
# 根据正则表达式搜索字符串,并返回匹配的字符串列表
        sentences = re.findall(sentence_pattern, article)
        matched_sentence = next((s for s in sentences if word in s), None)
        if matched_sentence:
            article = article.replace(matched_sentence, f"{matched_sentence}", 1)
            matched_sentences.append(matched_sentence)
        else:
            unmatched_keywords.append(word)
    else:
        unmatched_keywords.append(word)

with open('unmatched_keywords.txt', 'w') as file:
    for word in unmatched_keywords:
        file.write(word + '\n')
with open("sentences.txt", "w") as file:
    file.write('\n'.join(matched_sentences))
with open('matched_keywords.txt', 'w') as file:
    for word in matched_keywords:
        file.write(word + '\n')
with open("new.txt", "w") as file:
    file.write(article)

  • 以下回答由chatgpt基于相关博客总结生成:

    要修改代码以按照关键词在文章中出现的顺序排列生成的句子,可以按照以下步骤进行操作:

    1. 创建一个空的列表(句子列表)和一个空的字典(句子字典)。
    2. 将每个段落(paragraph)拆分为句子,并将每个句子与其所在的段落号放入句子列表中。可以使用常用的句子拆分器来实现这一步骤。
    3. 使用关键词匹配算法,将关键词与句子列表中的句子进行匹配。
    4. 对匹配到的句子进行排序,按照关键词在文章中出现的顺序排序。
    5. 将排序后的句子和其所在的段落号存储在句子字典中。
    6. 按照段落号的顺序遍历句子字典,并将每个句子输出或保存到文件中。

    以下是一个示例代码,演示了如何实现以上步骤: ```python import re

    def split_paragraphs(text): # 此函数将文本拆分为段落列表 paragraphs = re.split('\n\n', text) return paragraphs

    def split_sentences(paragraph): # 此函数将段落拆分为句子列表 sentences = re.split('(?<!\w.\w.)(?<![A-Z][a-z].)(?<=.|\?)\s', paragraph) return sentences

    def match_keywords(sentences, keywords): # 此函数将关键词与句子列表进行匹配,并返回匹配到的句子字典 matched_sentences = {} for i, sentence in enumerate(sentences): for keyword in keywords: if keyword in sentence: if i in matched_sentences: matched_sentences[i].append(sentence) else: matched_sentences[i] = [sentence] break return matched_sentences

    def sort_sentences(matched_sentences): # 此函数根据关键词在文章中出现的顺序对句子字典进行排序 sorted_sentences = {} for key in sorted(matched_sentences.keys()): sorted_sentences[key] = matched_sentences[key] return sorted_sentences

    def generate_ordered_sentences(text, keywords): paragraphs = split_paragraphs(text) sentences = [] for paragraph in paragraphs: sentences.extend(split_sentences(paragraph)) matched_sentences = match_keywords(sentences, keywords) sorted_sentences = sort_sentences(matched_sentences) ordered_sentences = [] for key in sorted_sentences.keys(): ordered_sentences.extend(sorted_sentences[key]) return ordered_sentences

    示例输入文本和关键词

    text = ''' 段落0: 试论因子的筛选,股票期货策略,以及基于多因子策略的机器学习算法 前言正文股票因子的筛选股票期货策略基于多因子策略的机器学习

    段落1: 全文预览 熟悉一些图像形态学处理方法图像的直方图与均衡化操作傅里叶变换图像梯度与边缘检测练习代码(全)imgPreprocessing4.pyimgPreprocessing5.py

    段落2: 例子一【数学函数的表出】 (1)数学模型 数学模型f(x)=sinx1+cosx2,取f(x)的最小值可以表达成目标函数min(sinx1+cosx2) (2)约束条件 1)边界约束【也称为box约束】:2< x1 <10 ,同时满足3 <x2 <5 2) 非线性不等式约束:x1*x1-sinx2>1 3)非线性等式约束:x1+x2=1

    段落3: 2.4 对于当前处理过的数据集,划分训练集和测试集,并设置好随机种子等其他参数。 X_train,X_test,Y_train,Y_test = train_test_split(stu_data.iloc[:,:-1], stu_data['G3'],test_size=0.3,random_state=5)

    段落4: 熟悉一些图像形态学处理方法 使用软件:pycharm,主要涉及到的操作包括开运算、闭运算、梯度运算、礼帽与黑帽运算等操作。 具体运行结果截图如下。 猫猫探头!

    小狗饼干->饼干变质orz

    段落5: 2.1 引入权值因子 基本 GWO 算法通过计算三个最佳灰狼位置的平均值来更新灰狼位置,这种策略并没有考虑三头狼在群体狩猎活动中的贡献度问题。由于 GWO 算法的 狼 α 并不一定是全局最优解,这时在不断迭代中,随着其余狼 ω 向这三头狼逼近,这就容易陷入局部最优 。本文从最佳灰狼贡献问题角度设计一种权重因子,用来提升GWO算法的寻优能力。由于GWO算法中的系数向量 A 和 C 是动态随机的,而权重因子也应该随着寻优过程非线性调整变化,为此本文设计的权重因子来源于系数向量 AAA 和 CCC 。在基本 GWO\mathrm{GWO}GWO 算法中, A1、A2、A3A_{1} 、 A_{2} 、 A_{3}A1​、A2​、A3​ 以及 C1C_{1}C1​ 、 C2、C3\boldsymbol{C}{2} 、 \boldsymbol{C}C2​、C3​ 是不相同的,在这里为了保证权重因子更新的相关联 性, 设计 A1、A2\boldsymbol{A}{1} 、 \boldsymbol{A}A1​、A2​ 和 A3\boldsymbol{A}_{3}A3​ 相同, C1、C2\bold

问题点: 使得 sentences 是按照出现在文章中的顺序排列
分析思路:
①目前处理顺序受到keyword列表的影响.
②re.findall只返回关键字的所有匹配项的列表.

处理方案:
①修改正则匹配方法,获取关键字的所有位置参数信息
②通过对所有关键字的位置参数信息来对sentences获取结果进行排序.
正则匹配代码修改如下:

for i in re.finditer(keyword, article):
    # 匹配的关键项
    print(i.group())
    # 出现的起始位置和结束位置
    print(i.start(), i.end())