【发布时间】:2018-12-21 08:56:57
【问题描述】:
我是 Python 的新手,目前正在做一个小型测试用例分配,我要在其中找到字典键并将其匹配到一个小文本文件,并查看这些键是否存在于文本文件中。
字典如下:
dict = {"描述,翻译": "test_translation(serial,",
"unit": "test_unit(",}
文本文件中的文本,以下称为“requirement.txt”:
描述应显示XXX的翻译。
该单位应被隐藏。
该值是从文件“version.txt”中读取的。
关键是,如果它们存在或不存在,我要查找并匹配 - 匹配应该返回“测试通过”,没有匹配会返回跳过。
字典中的键将被排序到一个列表中,然后迭代并匹配到文本。 (字典中的值将被排序到一个单独的列表中,并在一个单独的文件上进行迭代,我不会在这里深入研究。)
这是我目前拥有(并且卡住)的代码:
list = sorted(key_words.keys(), key=lambda d: d[0])
with open('C:/Users-------/requirement.txt', 'r') as outfile:
lines = outfile.readlines()
for line in lines:
line = line.strip()
if line == '':
continue
line_strings = line.split(' ')
for word in list:
if word in line:
print("Test Pass")
print(word)
break
else:
print("Test Fail")
print(line + "\n")
目前得到的结果:
Test Fail
Test Pass
display
The description shall display the translation of XXX.
Test Fail
Test Fail
Test Fail
Test Pass
unit
The unit shall be hidden.
Test Fail
Test Fail
Test Fail
Test Fail
The value is read from the file "version.txt".
使用我拥有的当前代码(并且我被卡住了),运行多次“测试通过”和“测试失败”返回的代码,这表明键在每一行上迭代多次并返回结果对于每个多次迭代。
我被困在两个方面:
- 将key拆分成列表后,如何按照“描述、翻译”、“单元”的顺序排列?
- 如何修改代码以保证返回一次结果为“Test pass”或“test fail”
理想情况下,结果应以以下格式返回:
理想的结果:
('Text:', "The description shall display the translation of XXX.
('Key:', 'description, translation')
Test Pass
('Text:', 'The unit shall be hidden.')
('Key:', 'unit')
Test Pass
('Text:', 'The value is read from the file "version.txt".')
('Key:', (none))
Test Fail
请多多指教,谢谢!
【问题讨论】:
标签: dictionary pattern-matching string-matching testcase