在 Python 中特定行的字符串中查找数字

Finding a number in a string on a specific line in Python

我面临着创建一个读取文本文件的程序的挑战。这个程序还需要在文本文件中找到某些东西,我已经想出了如何对文件进行基本的读取和搜索。在完成基本的读取和搜索之后,它会获取最相关的信息,并将其放入各自的文本文件中。这是它开始变得麻烦的地方。假设我正在使用 Raspi 配置,我正在阅读的 txt 将如下所示:

# Set sdtv mode to PAL (as used in Europe)
sdtv_mode=2
# Force the monitor to HDMI mode so that sound will be sent over HDMI cable
hdmi_drive=2
# Set monitor mode to DMT
hdmi_group=2
# Set monitor resolution to 1024x768 XGA 60 Hz (HDMI_DMT_XGA_60)
hdmi_mode=16
# Make display smaller to stop text spilling off the screen
overscan_left=20
overscan_right=12
overscan_top=10
overscan_bottom=10

提取我需要的所有变量名后,我只需要从该文件中提取数字。这就是我被困的地方。现在我正试图找到过度扫描的数字,我找到了它们的位置,但我需要知道这个值。

def findOverScan(beg, end):
    for num, line in enumerate(conf):
        if re.match("overscan(.*)", line):
            if num > beg and num < end:
                lineNum.append(num)

这让我可以找到行号。我不确定我应该怎么做才能找到这个号码。我不会复制并粘贴整个内容,因为我正在创建一个文件供另一个程序读取以将所有内容输入数据库。

我之前在程序中打开配置,因为我多次使用它,多次重新打开它没有意义。 findOverScan 的参数只是它要查看的开始和结束行。

您可以使用正则表达式捕获组来提取过扫描类型和等号后的数字。

a = 'overscan_left=20'
b = re.match('overscan_([^=]+)=([0-9]+)',a)
if b:
    print b.groups()

输出:

('left', '20')

您需要将 '20' 字符串表示形式转换为具有 int(b.groups()][1]) 的整数。

要将您的配置文件解析为 dict,您可以使用

def read_config(conf):
    config = {}
    for line in conf:
        line = line.strip()
        if line.startswith('#'):
            continue
        varname, value = line.split('=')
        config[varname] = value
    return config

这给了你 print(read_config(filecontent)):

{'hdmi_drive': '2',
 'hdmi_group': '2',
 'hdmi_mode': '16',
 'overscan_bottom': '10',
 'overscan_left': '20',
 'overscan_right': '12',
 'overscan_top': '10',
 'sdtv_mode': '2'}

如果所有值都是整数,您可以添加 int(value)