使用 Python 正则表达式按换行符或句点划分字符串 [英] Divide string by line break or period with Python regular expressions

查看:24
本文介绍了使用 Python 正则表达式按换行符或句点划分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

"""你好,很高兴认识你.我的名字是鲍勃."""

我正在尝试找到将其拆分为按句点和换行符划分的列表的最佳方法:

["你好", "很高兴认识你", "我叫鲍勃"]

我很确定我应该使用正则表达式,但是,由于没有使用它们的经验,我正在努力弄清楚如何做到这一点.

解决方案

你不需要正则表达式.

<预><代码>>>>txt = """你好,很高兴认识你.... 我的名字是鲍勃.""">>>txt.split('.')['你好', "很高兴认识你", '\n我叫鲍勃', '']>>>[x for x in map(str.strip, txt.split('.')) if x]['你好', "很高兴认识你", '我叫鲍勃']

I have a string:

"""Hello. It's good to meet you.
My name is Bob."""

I'm trying to find the best way to split this into a list divided by periods and linebreaks:

["Hello", "It's good to meet you", "My name is Bob"]

I'm pretty sure I should use regular expressions, but, having no experience with them, I'm struggling to figure out how to do this.

解决方案

You don't need regex.

>>> txt = """Hello. It's good to meet you.
... My name is Bob."""
>>> txt.split('.')
['Hello', " It's good to meet you", '\nMy name is Bob', '']
>>> [x for x in map(str.strip, txt.split('.')) if x]
['Hello', "It's good to meet you", 'My name is Bob']

这篇关于使用 Python 正则表达式按换行符或句点划分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆