我有一个包含以下行的文件:
lines.txt
1. robert
smith
2. harry
3. john我想像下面这样获取数组:
["robert\nsmith","harry","john"]我尝试了这样的东西:
with open('lines.txt') as fh:
m = [re.match(r"^\d+\.(.*)",line) for line in fh.readlines()]
print(m)
for i in m:
print(i.groups())它输出以下内容:
[<_sre.SRE_Match object; span=(0, 9), match='1. robert'>, None, <_sre.SRE_Match object; span=(0, 8), match='2. harry'>, <_sre.SRE_Match object; span=(0, 7), match='3. john'>]
(' robert',)
Traceback (most recent call last):
File "D:\workspaces\workspace6\PdfGenerator\PdfGenerator.py", line 5, in <module>
print(i.groups())
AttributeError: 'NoneType' object has no attribute 'groups'看起来我处理这个问题的方式是非常错误的。你将如何解决这个问题?
发布于 2018-07-31 20:33:19
您可以将文件读入内存并使用
r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)'请参阅regex demo
详细信息
(?ms) -启用组和组modes^ - line\d+ - 1+ _ digits\. -a dot\s* -1+_ 0+ -组1(这是re.findall在这里返回的内容):任何字符,直到(但不包括)第一个出现的0+ -1+-0+行的开始,结束数字和.| - or\Z - string.结束
Python:
with open('lines.txt') as fh:
print(re.findall(r'(?ms)^\d+\.\s*(.*?)(?=^\d+\.|\Z)', fh.read()))发布于 2018-07-31 20:39:26
使用re.findall查找从\d\.\s+模式到下一个'\n\d‘模式或直到结束的所有内容
>>> import re
>>> re.findall(r'\d+\.\s+(.*?(?=\n\d|$))', text, flags=re.DOTALL)
['robert\n smith', 'harry', 'john']发布于 2018-07-31 20:54:03
您可以使用re.split。
Regex:\n?\d+\.\s*
详细信息:
\n - Newline? -匹配0到1次,match if 'new line‘exists\d+ -匹配1到无限次之间的数字(+) times\. - Dot\s* -匹配0到无限次之间的任何空白字符(等于[\r\n\t\f\v ]) (*) Python代码
re.split(r'\n?\d+\.\s*', lines)[1:][1:]删除第一项,因为它是空字符串
输出:
['robert\n smith', 'harry', 'john']https://stackoverflow.com/questions/51613428
复制相似问题