python - 选择列表中包含的子字符串(没有语法字符)
问题描述
我正在尝试查找和格式化列表中包含的单词。
以下是我尝试过的:
word_list = ['Penny', 'cat', 'carnival']
example_string= "I took my dog Penny and my cat, to the carnival."
formatted_text = " ".join(["<b>{}</b>".format(word) if word.strip(' , . ; :;\ " ()[]{}') in word_list else word for (i, word) in enumerate(example_string.split(" "))])
输出:我带着我的狗Penny和我的猫去狂欢节。
期望的输出:我带着我的狗Penny和我的猫去狂欢节。
基本上我想迭代字符串中的每个单词,如果单词在列表中,则对其进行格式化,而不格式化句点、逗号、引号等标点符号。有没有办法做到这一点?
解决方案
尝试:-
word_list = ['Penny', 'cat', 'carnival']
example_string = "I took my dog Penny and my cat, to the carnival."
for x in word_list:
example_string = example_string.replace(x, "<b>" + x + "</b>")
print(example_string)
输出:-
I took my dog <b>Penny</b> and my <b>cat</b>, to the <b>carnival</b>.
在浏览器上查看时:-
我带着我的狗Penny和我的猫去狂欢节。
推荐阅读
- r - 合并两个行值
- selenium - 无法选择按钮以使用硒单击它
- python - Starlette - uvicorn - 石墨烯异常记录
- reactjs - 遍历项目并将每个项目分配给 material-ui 增长组件
- vb.net - 是否有替代挂钩来检测 Windows 窗体之外的事件?
- angular - child.snapshot.issue angular 我无法从激活的路由中获取数据
- java - 如何使用spring boot对文档的数组大小(包括父项)求和?
- openshift - Tekton 任务不扩展参数 (OpenShift)
- javascript - 自定义路由组件从不匹配确切路径=“/”
- bootstrap-5 - 引导颜色变量