python - 如何在python中使用正则表达式为字符串插入类似标签 "<s></s>"的html?

标签 python regex

我正在处理一个文本语料库,其中包含三个句子。我想插入像标签<s>这样的html在开始和 </s>在每个句子的末尾使用正则表达式。下面给出部分代码:

text = '''
       I live in SOME_PLACE.
       I am a graduate student.
       My school is in SOME_PLACE.
       '''

我想要的是一个格式化为的Python字符串,

text_new = '<s> I live in SOME_PLACE. </s> <s> I am a graduate student. </s> <s> My school is in SOME_PLACE. </s>'

即我希望提及句子边界。请大家提出宝贵的建议。

最佳答案

以下应该有效:

text = '''
       I live in SOME_PLACE.
       I am a graduate student.
       My school is in SOME_PLACE.
       '''

text_new = ' '.join('<s> {} </s>'.format(l.strip()) for l in text.splitlines() if len(l.strip()))
print text_new

或者作为正则表达式:

import re
print re.sub(r'^\s+(.*)\n', r'<s> \1 </s> ', text, flags=re.M)

这将显示以下内容:

<s> I live in SOME_PLACE. </s> <s> I am a graduate student. </s> <s> My school is in SOME_PLACE. </s>

关于python - 如何在python中使用正则表达式为字符串插入类似标签 "<s></s>"的html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35369046/

相关文章:

regex - 如何从像abc****ef****这样的字段中选择?

python - 如何验证传递参数的总数?

python - 编译 forpy 以在 Fortran 中调用 Python 对象

python - PMML GBDTLRClassifier 中的分类特征设置错误

python - 我需要过滤或删除文件中的一些行

regex - Linux命令行从文本中提取名称

c# - 如何获取字符串的最后一部分?

python - 按周划分 Pandas Dataframe

regex - 删除文本文件中从第一个空行开始的所有内容

c# - 正则表达式只允许 100 到 999999 之间的数字