Python使用键从文本中提取值

Python使用键从文本中提取值,python,Python,我有一个文本文件,格式如下:Key-Value --START-- FirstName Kitty LastName McCat Color Red random_data Meow Meow --END-- 我想将文本中的特定值提取到变量或dict中。例如,如果我想提取LastName和Color的值,最好的方法是什么 random_data可能位于文件中的任何位置,并且跨越多行 我曾考虑过使用正则表达式,但我关心的是性能和可读性,因为在实际代码中,我有许多不同的键要提取 我也可以在每一行上

我有一个文本文件,格式如下:
Key-Value

--START--
FirstName Kitty
LastName McCat
Color Red
random_data
Meow Meow
--END--
我想将文本中的特定值提取到变量或dict中。例如,如果我想提取
LastName
Color
的值,最好的方法是什么

random_data
可能位于文件中的任何位置,并且跨越多行

我曾考虑过使用正则表达式,但我关心的是性能和可读性,因为在实际代码中,我有许多不同的键要提取

我也可以在每一行上循环,检查每一个键,但如果有10多个键,那就相当混乱了。例如:

if line.startswith("LastName"):
    #split line at space and handle
if line.startswith("Color"):
    #split line at space and handle

希望有更干净的东西

假设您的文件是一个名为sampletxt.txt的文件,这就行了。它从键->值列表创建字典映射

tokens = ['LastName', 'Color']  
dictResult = {} 
with open(fileName,'r') as fileHandle: 
   for line in fileHandle:
      lineParts = line.split(" ")
      if len(lineParts) == 2 and lineParts[0] in tokens:
           dictResult[lineParts[0]] = lineParts[1]
import re  
with open('sampletxt.txt', 'r') as f:
    txt = f.read()
keys = ['FirstName', 'LastName', 'Color']
d = {}
for key in keys:
    d[key] = re.findall(key+r'\s(.*)\s*\n*', txt)

此版本允许您选择指定令牌

import re
​
s = """--START--
FirstName Kitty
LastName McCat
Color Red
random_data
Meow Meow
--END--"""

tokens = ["LastName", "Color"]
if len(tokens) == 0:
    print(re.findall("({0}) ({0})".format("\w+"), s))
else:
    print( list((t, re.findall("{} (\w+)".format(t), s)[0]) for t in tokens))
输出
在其他答案的基础上,此函数将使用正则表达式获取任何文本键并返回值(如果找到):

import re
file_name = 'test.txt'

def get_text_value(text_key, file_name):
    match_str = text_key + "\s(\w+)\n"

    with open(file_name, "r") as f:
        text_to_check = f.readlines()

    text_value = None
    for line in text_to_check:

        matched = re.match(match_str, line)
        if matched:
            text_value = matched.group(1)

    return text_value

if __name__ == "__main__":

    first_key = "FirstName"
    first_value = get_text_value(first_key, file_name)
    print('Check for first key "{}" and value "{}"'.format(first_key,
                                                           first_value))

    second_key = "Color"
    second_value = get_text_value(second_key, file_name)
    print('Check for first key "{}" and value "{}"'.format(second_key,
                                                           second_value))

可以使用正则表达式获取LastName和Color。如果没有特定的标记,随机数据几乎不可能提取出来。我不太清楚,我想忽略
random\u数据
,并传递给它。我考虑过regex,但有点担心性能和可读性。理想情况下,我希望能够为extact定义一个令牌列表
tokens=['LastName','Color']
好吧,通常会问的第一个问题是你尝试了什么?更新了原始帖子。我想知道是否有比我发布的内容更清晰的内容FirstName或任何其他字段是否有多个实例?可能需要执行
re.findall()[0]
,否则该值是单个值的列表
import re
file_name = 'test.txt'

def get_text_value(text_key, file_name):
    match_str = text_key + "\s(\w+)\n"

    with open(file_name, "r") as f:
        text_to_check = f.readlines()

    text_value = None
    for line in text_to_check:

        matched = re.match(match_str, line)
        if matched:
            text_value = matched.group(1)

    return text_value

if __name__ == "__main__":

    first_key = "FirstName"
    first_value = get_text_value(first_key, file_name)
    print('Check for first key "{}" and value "{}"'.format(first_key,
                                                           first_value))

    second_key = "Color"
    second_value = get_text_value(second_key, file_name)
    print('Check for first key "{}" and value "{}"'.format(second_key,
                                                           second_value))