我有一个这样的文件:
Name: John Class: II Age: 8 Interest: Sports Name: Emma Class: III Hobby: Dance
所以我想读取这个文件并将内容放入一个名为key的字典中.这些部分的行数不尽相同.如何使用Robot Framework关键字实现此字典.
这是你需要的吗?
*** Settings *** Library OperatingSystem Library String Library Collections *** Test Cases *** Split File By Names ${my_dict} Create Dictionary ${data} Get File@{lines} Split To Lines ${data} Remove Values From List ${lines} ${EMPTY} :FOR ${line} IN @{lines} \ ${key} ${value} Split String ${line} : \ ${name} Set Variable If '${key}' == 'Name' ${value.strip()} ${name} \ Run Keyword If '${key}' == 'Name' Set To Dictionary ${my_dict} ${name}=@{EMPTY} \ Run Keyword If '${key}' <> 'Name' Append To List ${my_dict.${name}} ${line} Log ${my_dict}
无论如何,解析文件的RF方式很糟糕.我宁愿去蟒蛇.
#!/usr/bin/python # -*- coding: utf-8 -*- class ParseFile: def __init__(self): self.my_dict = {} def parse_file_to_dict(self): with open('') as f: lines = f.read().splitlines() for line in (l for l in lines if l != ""): key, value = line.split(":", 1) if key == "Name": name = value self.my_dict[name] = [] else: self.my_dict[name].append(line) return self.my_dict
......然后在RF中调用它.
*** Settings *** Library ParseFile.py *** Test Cases *** Do It In Python ${my_dict} Parse File To Dict Log ${my_dict}
请注意,这两种方式都严格依赖于您提供的数据结构.也就是说,如果"名称"不在每个部分的第一行,它将无法工作,需要对数据进行更多处理.