python - 将字符串与文本进行比较以在正确的位置设置标点符号
问题描述
因此,我们需要将这段文本中的一段文本和短语与标点符号匹配:
text = 'i like plums, apples, and donuts. if i had a donut, i would eat it'
phrases = [['apples and donuts'], ['a donut i would']]
我需要的输出是:
output = [['apples, and donuts'], ['a donut, i would']]
我是初学者,所以我正在考虑使用 .replace() 但我不知道如何对字符串进行切片并从文本中访问我需要的确切部分。你能帮我解决这个问题吗?(我不允许使用任何库)
解决方案
您可以为此尝试正则表达式
import re
text = 'i like plums, apples, and donuts. if i had a donut, i would eat it'
phrases = [['apples and donuts'], ['a donut i would']]
print([re.findall(i[0].replace(" ", r"\W*"), text) for i in phrases])
输出
[['apples, and donuts'], ['a donut, i would']]
通过迭代列表并用正则表达式方法phrases
替换空格将能够检测到搜索词并忽略标点符号。\W*
findall
推荐阅读
- python - 如何从 Django 中的外键值中取平均值?
- r - 子集 data.table 基于单独的 data.table
- c# - 为什么隐式转换在 C# 中不起作用
- c# - 单击按钮 c# 时获取管理员访问权限
- java - Eclipse IDE 无法在我的系统中启动
- java - Does it make sense to have a separate microservice for thread pool in Java?
- android - 如何在 React-Native 中仅获得数字键盘?
- git - 无法使用 git bash 将文件添加到 github
- javascript - 我不明白这种递归情况
- javascript - 提示存储问题