将文本文件号存储为Python变量

2024-06-07 17:52:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将文本文件中显示的数字提取到Python代码中的变量中

我想提取标有光盘位置X和Y的数字,并将它们保存到以下变量“od_X”和“od_Y”

以下是文本文件的结构:

Code version: $Id: GeneralProjection.m 5455 2017-09-19 12:54:06Z mverhoek $
Device model: California
Fovea Location Y (vertical): 1540
Fovea Location X (horizontal): 1980
Fovea Confidence: 0.686278
Optic Disc Location Y (vertical): 1520
Optic Disc Location X (horizontal): 1596
Optic Disc Confidence: 0.731152
Eye Laterality Prediction (L,R): L
Eye Steer Prediction (C,I,S,L,R): C
Projection Table Used: /media/dropbox/GeneralProjectionTables/California/otrans(0.75,0.88).mat
Maximum percent error in area measurement: 0.843522
Distance from fovea to transformation point in degrees: 0.788453

以下是我目前拥有的代码:

import re
for line in open('test.txt'):
    match = re.search('Optic Disc Location X (horizontal): (\d+)', line)
    if match:
        od_x = match.group(1)
        print(od_x)

for line in open('test.txt'):
    match = re.search('Optic Disc Location Y (vertical): (\d+)', line)
    if match:
        od_y = match.group(1)
        print(od_y)

我做错了什么?我的正则表达式有问题吗,或者我将结果分配给变量的方式有问题吗?谢谢:)


Tags: 代码inrematchline数字locationdisc
1条回答
网友
1楼 · 发布于 2024-06-07 17:52:23

您需要将正则表达式中的括号转义,以便将它们视为普通括号,而不是组。此外,最好使用原始字符串来避免转义问题。只需更改为:

import re
for line in open('test.txt'):
    match = re.search(r'Optic Disc Location X \(horizontal\): (\d+)', line)
    if match:
        od_x = match.group(1)
        print(od_x)

for line in open('test.txt'):
    match = re.search(r'Optic Disc Location Y \(vertical\): (\d+)', line)
    if match:
        od_y = match.group(1)
        print(od_y)

输出:

1596
1520

通过只读取一次文件并在同一个循环中测试两个正则表达式,可以稍微改进代码:

import re
  
re_x = re.compile(r'Optic Disc Location X \(horizontal\): (\d+)')
re_y = re.compile(r'Optic Disc Location Y \(vertical\): (\d+)')

with open('test.txt') as f:
    for line in f:
        match = re_x.search(line)
        if match:
            od_x = match.group(1)

        match = re_y.search(line)
        if match:
            od_y = match.group(1)

print(od_x)
print(od_y)

甚至,从Python 3.8开始,您可以使用新的:=操作符同时测试和分配匹配:

import re
  
re_x = re.compile(r'Optic Disc Location X \(horizontal\): (\d+)')
re_y = re.compile(r'Optic Disc Location Y \(vertical\): (\d+)')

with open('test.txt') as f:
    for line in f:
        if match := re_x.search(line):
            od_x = match.group(1)

        if match := re_y.search(line):
            od_y = match.group(1)

print(od_x)
print(od_y)

相关问题 更多 >

    热门问题