首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用空格和html突出显示动词短语

使用空格和html突出显示动词短语
EN

Stack Overflow用户
提问于 2018-08-28 09:31:21
回答 1查看 2.2K关注 0票数 3

我已经设计了一个代码,红色字体动词短语,并输出为HTML。

代码语言:javascript
复制
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)))

电流输出

代码语言:javascript
复制
The author **is writing** a new book. The dog is barking.The author is writing a new book. The dog **is barking.**

句子被重复了两次,第一个是书写,最后一个是叫声被检测到。

预期输出:

代码语言:javascript
复制
The author **is writing** a new book. The dog **is barking.**

在发送给列表检查之前,我应该做一个句子标记化吗?请帮帮忙?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-28 19:45:19

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

代码语言:javascript
复制
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)))

上面的代码将分别编写句子。如果你想把它写成一个句子,在写到一个文件之前,将修改附加到一个列表中,并将它们连接起来,如下所示。

代码语言:javascript
复制
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))

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52048905

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档