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

在Python中的特定行上查找字符串中的数字,python,raspberry-pi,raspbian,readfile,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 wi

我面临着创建一个读取文本文件的程序的挑战。这个程序还需要在文本文件中查找某些内容,我已经知道如何对文件进行基本的读取和搜索。在完成基本的读取和搜索之后,它将获取最相关的信息,并将其放入各自的文本文件中。这就是它开始变得麻烦的地方。假设我正在使用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)
def findOverScan(beg,结束): 对于num,枚举(conf)中的行: 如果重新匹配(“过扫描(.*),行): 如果num>beg和num 这允许我找到行号。我不确定该怎么做才能找到号码。我不是复制整个东西并粘贴它,因为我是为另一个程序创建一个文件来读取,以便将所有内容输入数据库


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

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

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

('left', '20')

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

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

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
这给你
打印(读取配置(文件内容))


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

要将配置文件解析为
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
这给你
打印(读取配置(文件内容))

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