我正在处理一个文本语料库,其中包含三个句子。我想插入像标签<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/