我有一张表格:
<textarea name="test">
假设用户输入以下文字:
This is the first paragraph
It has two lines
This is the second paragraph
我想把这个文本分成一个列表[“这是第一段\ n它有两行”,“这是第二段”]
我认为这样可行:
temp = self.request.get("test")
list = re.split(r'\n\n', temp)
但事实并非如此。然而,
temp = self.request.get("test")
list = re.split(r'\n', temp)
产生以下列表:[“这是第一行”,“”,“这是第二行”]
我错过了什么?
ALSO:
假设to文本之间可能有一个或两个空行,这是否有意义?
temp = self.request.get("test")
list = re.split(r'(\n){2,3}', temp)
解决方案:
在下面的帮助下,
我发现以下代码适用于我的情况:
temp = self.request.get("test")
list = [l for l in temp.split('\r\n\r\n') if l.split()]
我认为换行可能取决于输入来自哪个系统,因此它可能不是完美的解决方案。
答案 0 :(得分:5)
我认为re
模块可能有点矫枉过正。只需将内容拆分为\n
并删除空字符串。
>>> s = """This is the text
...
... I am interested in splitting,
...
...
... but I want to remove blank lines!"""
>>> lines = [l for l in s.split("\n") if l]
>>> lines
['This is the text', 'I am interested in splitting,', 'but I want to remove blank lines!']
string.split
似乎也快了两倍。
> python -m timeit -s 's = "This is the text\n\nthat I want to split\n\n\nand remove empty lines"; import re;' '[l for l in re.split(r"\n", s) if l]'
100000 loops, best of 3: 2.84 usec per loop
> python -m timeit -s 's = "This is the text\n\nthat I want to split\n\n\nand remove empty lines"' '[l for l in s.split("\n") if l]'
1000000 loops, best of 3: 1.08 usec per loop
答案 1 :(得分:1)
标准拆分可以包含多字符分隔符:
>>> '''1st para
... second line
...
... 2nd para
... '''.split('\n\n')
['1st para\nsecond line', '2nd para\n']
修改强>
这是一个re.split
,它可以处理Linux和Windows风格的行结尾,并处理段落之间的多个空行。
\n
测试:>>> x='this is\na multiline\ntest\n\n2nd para\ngraph\n\n\n\nmore\nmore\nmore\n\n\n\n\nmore\n'
>>> import re
>>> re.split(r'(?:\r?\n){2,}',x)
['this is\na multiline\ntest', '2nd para\ngraph', 'more\nmore\nmore', 'more\n']
\r\n
测试:>>> y=x.replace('\n','\r\n')
>>> re.split(r'(?:\r?\n){2,}',y)
['this is\r\na multiline\r\ntest', '2nd para\r\ngraph', 'more\r\nmore\r\nmore', 'more\r\n']