【发布时间】:2018-03-30 05:12:19
【问题描述】:
我正在尝试从文本文件中提取整行,但它没有按预期工作。
示例文本文件内容:
data = """Add TTFF LEVERERGE 30 mp -5%
Some Text, Some Text
5882950 Abc Lahd
Pos Sequence Batch datax datay dataz dataa datab
1 00061680 904834 20.35 REV 177,650 5329,50
Bundled 2-rev 42al/xyz
Neon Classic Unit 1300 abc \ 1638\48
2 00012815 55244 815 FWD 164,720 18448,64
UnBundled 2-pag
Mathrine Classic straight Tilt 2 xyz / 23,2x23gb
150st/xyz 20 abc/xyz
3 90072815 65944 212 KRT 164,720 18448,64
UnBundled 2-pag
Mathrine Classic straight Tilt 2 xyz / 23,2x23gb
150st/bunt 20 bunt/bal
Some Valid Text
Some More Valid Text Some More Valid Text"""
我希望列表格式的所有三行都从中提取特定值。
逻辑是:
- 在我们开始新行之前停止提取
- 每一行都有一个序列数字(1、2、3、...、99.等)
- 考虑以“一些有效文本”结尾的最后一行的结尾
(由于前 2 个步骤不起作用,因此 re.findall 中的 #3 此步骤不考虑正则表达式)
$re.findall(r'(^\d{1,2}\s.*?\n^\d)', data, re.DOTALL|re.M)
['1 00061680 904834 20.35 REV 177,650 5329,50\nBundled 2-rev 42al/xyz\nNeon Classic Unit 1300 abc \\ 1638\x048\n2',
'3 90072815 65944 212 KRT 164,720 18448,64\nUnBundled 2-pag\nMathrine Classic straight Tilt 2 xyz / 23,2x23gb\n1']
预期结果是:
['1 00061680 904834 20.35 REV 177,650 5329,50\nBundled 2-rev 42al/xyz\nNeon Classic Unit 1300 abc \\ 1638\x048\n',
'2 00012815 55244 815 FWD 164,720 18448,64\n UnBundled 2-pag\n Mathrine Classic straight Tilt 2 xyz / 23,2x23gb\n 150st/xyz 20 abc/xyz',
'3 90072815 65944 212 KRT 164,720 18448,64\nUnBundled 2-pag\nMathrine Classic straight Tilt 2 xyz / 23,2x23gb\n150st/bunt 20 bunt/bal']
从文本中提取行的任何指导/帮助?
【问题讨论】:
-
发布最终预期结果
-
@RomanPerekhrest - 已编辑,感谢您的建议
-
好的,如果行以
2 text ...., 7 text .... , 10 text, 3 text ...而不是1 .... 2 ... 3 ...之类的无序数字开头怎么办?
标签: python regex python-3.x