我设计了一个红色字体动词短语的代码,并将其输出为html。

from __future__ import unicode_literals
import spacy,en_core_web_sm
import textacy
import codecs
nlp = en_core_web_sm.load()
sentence = 'The author is writing a new book. The dog is barking.'
pattern = r'<VERB>?<ADV>*<VERB>+'
doc = textacy.Doc(sentence, lang='en_core_web_sm')
lists = textacy.extract.pos_regex_matches(doc, pattern)
with open("my.html","w") as fp:
    for list in lists:
        search_word = (list.text)
        fp.write(sentence.replace(search_word, '<span style="color: red">{}</span>'.format(search_word)))

电流输出
The author **is writing** a new book. The dog is barking.The author is writing a new book. The dog **is barking.**

这个句子被重复两次,第一次是写,最后一次是吠叫。
预期产量:
The author **is writing** a new book. The dog **is barking.**

在发送到列表检查之前,我需要做一个句子标记吗?请帮忙?

最佳答案

找到了另一种更符合逻辑的方法。与其在整句中替换,不如在有句型的句子中替换。

with open("my.html","w") as fp:
for _list in lists:
    search_word = (_list.text)
    containing_sentence = [i for i in sentence.split('.') if str(search_word) in str(i)][0]
    fp.write(containing_sentence.replace(search_word, '<span style="color: red">{}</span>'.format(search_word)))

以上代码将分别写出句子。如果要将其作为一个句子执行,请将修改内容附加到列表中,并在写入文件之前将其合并,如下所示。
mod_sentence = []
for _list in lists:
    search_word = (_list.text)
    containing_sentence = [i for i in sentence.split('.') if str(search_word) in str(i)][0]+'.'
    mod_sentence.append(containing_sentence.replace(search_word, '<span style="color: red">{}</span>'.format(search_word)))
with open("my.html","w") as fp:
    fp.write(''.join(mod_sentence))

希望这有帮助!干杯!

10-08 10:53