我正在寻找一种从文本文件中提取表数据以进行进一步处理的通用方法。到目前为止,我一直在尝试正则表达式,但很难创建一个通用的正则表达式来匹配任何类型的表。
例如,以下表达式$(AMDAPPSDKROOT)\lib\x86
可以获得具有7个重复结构的行,并且可能适用于具有7列但不包含其他表的某些表。
我希望这可以使用任何表格类型的数据。
例如,如果给出以下文件,我们如何只获得与r'\s*([\d.\w]+)[ \h]+([\d.\w]+)[ \h]+([\d.\w]+)[ \h]+([\d.\w]+)[ \h]+([\d.\w]+)[ \h]+([\d.\w]+)[ \h]+([\d.\w]+)[ \h]*'
下的数字块相关联的文本:
Peak Retention Time .. Area
这个问题是否有正则表达式,模式识别包或其他类型的(最好是python)包解决方案?
答案 0 :(得分:1)
import re
chem = open('chem.txt', 'r')
pattern = r'\s+\d+\s+([\d.]+)\s+[A-Z]+\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)'
for l in chem.readlines():
match = re.search(pattern, l)
if match:
ret_time, width, area_pas, height, area_pct = match.group(1), match.group(2), match.group(3), match.group(4), match.group(5)
#write these to file??
print (ret_time, width, area_pas, height, area_pct)
您可能需要重构并添加异常处理