【问题标题】:Highlight verb phrases using spacy and html使用 spacy 和 html 突出显示动词短语
【发布时间】:2019-02-02 13:23:43
【问题描述】:

我设计了一个红色字体动词短语的代码并将其输出为 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.**

在将其发送到列表检查之前,我是否必须进行句子标记化?请帮忙?

【问题讨论】:

    标签: html beautifulsoup nltk spacy


    【解决方案1】:

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

    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))
    

    希望这会有所帮助!干杯!

    【讨论】:

    • 我已经建议了一个解决方案作为问题的文本。现在也编辑了。尝试第二个块。
    • 另一个观察结果。最后一句缺少句号。
    • 我用句号来分割句子,所以它们不见了。现在我已将它添加到 containing_sentence 本身。这将解决问题。
    • 仅供参考:使用诸如list 之类的关键字作为变量名被认为是一种反模式,只是为新编码人员突出显示它。
    猜你喜欢
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多