首页 > 解决方案 > 在外部文件中搜索特定单词并将下一个单词存储在 Python 中的变量中

问题描述

我有一个文件,其中包含与此类似的行:

"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')

用于搜索。但不能超越这一点。

标签: pythonfilesearchmaya

解决方案


我建议使用正则表达式来提取值:

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)



推荐阅读