在外部文件中搜索特定单词,然后将下一个单词存储在Python中的变量中

问题描述 投票:-1回答:1

我有一个与该行相似的文件:

"string" "playbackOptions -min 1 -max 57 -ast 1 -aet 57

现在我要搜索文件,并提取并将“ -aet”(在本例中为57)之后的值存储在变量中。

我正在使用

import mmap

with open('file.txt') as f:
    s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
    if s.find('-aet') != -1:
        print('true')

用于搜索。但不能超出此范围。

python file search maya
1个回答
1
投票

我建议使用regular expressions提取值:

import re

# Open the file for reading
with open("file.txt", "r") as f:
    # Loop through all the lines:
    for line in f:
        # Find an exact match
        # ".*" skips other options,
        # (?P<aet_value>\d+) makes a search group named "aet_value"
        # if you need other values from that line just add them here
        line_match = re.search(r"\"string\" \"playbackOptions .* -aet (?P<aet_value>\d+)", line)
        # No match, search next line
        if not line_match:
            continue
        # We know it's a number so it's safe to convert to int
        aet_value = int(line_match.group("aet_value"))
        # Do whatever you need
        print("Found aet_value: {}".format(aet_value)


© www.soinside.com 2019 - 2024. All rights reserved.