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

时间:2016-07-05 16:04:54

标签: python raspberry-pi raspbian readfile

我面临着创建一个读取文本文件的程序的挑战。这个程序还需要在文本文件中找到某些东西,我已经想出了如何对文件进行基本读取和搜索。在完成基本读取和搜索之后,它将获取最相关的信息,并将其放入其各自的文本文件中。这是它开始令人不安的地方。假设我使用的是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的参数只是它的开始和结束行。

2 个答案:

答案 0 :(得分:4)

要将配置文件解析为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)

答案 1 :(得分:1)

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

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

输出:

('left', '20')

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

相关问题