我正在读取一个文件,其中包含以下示例的行
[ 0 ] L= 9 (D) R= 14 (D) p= 0.0347222 e= 10 n= 34
我看到了Matlab code阅读由
给出的文件[I,L,Ls,R,Rs,p,e,n] = textread(f1,'[ %u ] L= %u%s R= %u%s p= %n e=%u n=%u')
我想用 Python 读取这个文件。我唯一知道的是正则表达式,即使阅读这一行的一部分也会导致类似
re.compile('\s*\[\s*(?P<id>\d+)\s*\]\s*L\s*=\s*(?P<Lint>\d+)\s*\((?P<Ltype>[DG])\)\s*R\s*=\s*(?P<Rint>\d+)\s*')
太丑了!在 Python 中有更简单的方法吗?
最佳答案
您可以通过使用转义/替换来构建正则表达式,使其更具可读性...
number = "([-+0-9.DdEe ]+)"
unit = r"\(([^)]+)\)"
t = "[X] L=XU R=XU p=X e=X n=X"
m = re.compile(re.escape(t).replace("X", number).replace("U", unit))
关于python - 如何在 python 中将文本格式与没有正则表达式的字符串匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668904/