簡體   English   中英

在外部文件中搜索特定單詞並將下一個單詞存儲在 Python 中的變量中

[英]Search external file for specific word and store the very next word in variable in 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')

用於搜索。 但不能超越這一點。

我建議使用正則表達式來提取值:

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)


這是使用本機字符串和列表方法的另一種方法,因為當我有一段時間沒有接觸它時,我通常會忘記正則表達式語法:

tag = "-aet"  # Define what tag we're looking for.

with open("file.txt", "r") as f:  # Read file.
    for line in f:  # Loop through every line.
        line_split = line.split()  # Split line by whitespace.

        if tag in line_split and line_split[-1] != tag:  # Check if the tag exists and that it's not the last element.
            try:
                index = line_split.index(tag) + 1  # Get the tag's index and increase by one to get its value.
                value = int(line_split[index])  # Convert string to int.
            except ValueError:
                continue  # We use try/except in case the value cannot be cast to an int. This may be omitted if the data is reliable.

            print value  # Now you have the value.

基准測試會很有趣,但通常正則表達式較慢,因此這可能會執行得更快,尤其是在文件特別大的情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM