我正在处理一个文本,其中删除了所有“\ n”(将两个单词合并为一个,例如“我喜欢香蕉,这是一条新线和另一个。”)我现在要做的就是告诉Python寻找一个小写字母组合,后跟大写字母/标点符号,后跟大写字母并插入一个空格。拆分python中的合并单词
我认为这对reg很简单。表达式,但它不是 - 我找不到一个“插入”函数或任何东西,并且字符串命令似乎也没有帮助。我该怎么做呢? 任何帮助将不胜感激,我绝望的在这里......
谢谢,帕特里克
我正在处理一个文本,其中删除了所有“\ n”(将两个单词合并为一个,例如“我喜欢香蕉,这是一条新线和另一个。”)我现在要做的就是告诉Python寻找一个小写字母组合,后跟大写字母/标点符号,后跟大写字母并插入一个空格。拆分python中的合并单词
我认为这对reg很简单。表达式,但它不是 - 我找不到一个“插入”函数或任何东西,并且字符串命令似乎也没有帮助。我该怎么做呢? 任何帮助将不胜感激,我绝望的在这里......
谢谢,帕特里克
尝试以下操作:
re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", your_string)
例如:
import re
lines = "I like bananasAnd this is a new line.And another one."
print re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", lines)
# I like bananas And this is a new line. And another one.
如果要插入新行,而不是空间,更换为r"\1\n\2"
。
您正在寻找的sub
功能。有关文档,请参见http://docs.python.org/library/re.html。
嗯,有趣。您可以使用正则表达式的sub()
function替换文本:
>>> import re
>>> string = 'fooBar'
>>> re.sub(r'([a-z][.!?]*)([A-Z])', r'\1 \2', string)
'foo Bar'
多德。美元符号不是你插入组的方式。 :-) – 2011-03-20 03:14:52
@Brandon:是的,刚刚意识到,谢谢。仍在思考Perl ;-) – Cameron 2011-03-20 03:15:27
使用re.sub
你应该能够作出这样的劫掠小写和大写字母和替代他们相同的两个字母的模式,但在之间的空间:
import re
re.sub(r'([a-z][.?]?)([A-Z])', '\\1\n\\2', mystring)
这似乎产生以下内容:我喜欢banana \ 1 \ n \ 2nd这是一个新的lin \ 1 \ n \第二个另一个。为了解决这个问题,使用\ 1 \ n \ 2 – Tom 2011-03-20 03:28:51
Tom替换部分,我想你可能会在我的示例中尝试使用时意外地在第二个字符串常量前加了一个'r'字符。 Python字符串“\\ 1 \ n \\ 2”是一系列字符'\ 1
如果你真的不除了在句子的开始处有任何大写字母,它可能是最简单的循环字符串。
>>> import string
>>> s = "a word endsA new sentence"
>>> lastend = 0
>>> sentences = list()
>>> for i in range(0, len(s)):
... if s[i] in string.uppercase:
... sentences.append(s[lastend:i])
... lastend = i
>>> sentences.append(s[lastend:])
>>> print sentences
['a word ends', 'A new sentence']
这里的另一种方法,避免了正则表达式和不使用任何进口图书馆,只是内置插件...
s = "I like bananasAnd this is a new line.And another one."
with_whitespace = ''
last_was_upper = True
for c in s:
if c.isupper():
if not last_was_upper:
with_whitespace += ' '
last_was_upper = True
else:
last_was_upper = False
with_whitespace += c
print with_whitespace
产量:
I like bananas And this is a new line. And another one.
非常感谢你,你刚刚救了我的周末! – patrick 2011-03-20 04:20:46