python文本文件变量搜索

时间:2016-01-12 23:48:33

标签: python

我有一个看起来像这样的文本文件

Apples: 01, Oranges: 33, Grapes: 07, Plums: 15

我想要做的是有一个函数,它检查所需的字符串是否在文本文件中,然后在它旁边拉出正确的数量。到目前为止我已经

def get_numbers(fruit)
  if fruit in open('example.txt'):
    #this is where im stuck on getting the correct value
    # if grapes were passed, how will i obtain 07?
  else:
    print 'some type of error'

1 个答案:

答案 0 :(得分:2)

我建议您构建一个字典,将水果名称映射到金额,然后从那里开始。

>>> with open('example.txt') as f:
...     result = {k:int(v) for k,v in re.findall('([^:\s]+):\s*(\d+)', f.read())}
... 
>>> result
{'Grapes': 7, 'Plums': 15, 'Apples': 1, 'Oranges': 33}
>>> 'Grapes' in result
True
>>> 'Bananas' in result
False
>>> result['Grapes']
7    

example.txt的内容为

  

苹果:01,橘子:33,葡萄:07,李子:15