首页 > 解决方案 > 将字符串与文本进行比较以在正确的位置设置标点符号

问题描述

因此,我们需要将这段文本中的一段文本和短语与标点符号匹配:

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() 但我不知道如何对字符串进行切片并从文本中访问我需要的确切部分。你能帮我解决这个问题吗?(我不允许使用任何库)

标签: pythonpython-3.xstringslice

解决方案


您可以为此尝试正则表达式

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


推荐阅读