[英]How to read a text file to find a value using a function built in python
I have a function that reads in a list.我有一个读入列表的函数。 it will iterate through the list and use that as the function input.它将遍历列表并将其用作函数输入。 It reads a text file that only contains 2 lines.它读取一个仅包含 2 行的文本文件。
LC1 LC1
LC2 LC2
import re
def dict(input):
for line in file:
if re.search(input,line):
print(input)
d[input]=None
else:
print(d)
break
file = open("Text.txt",'r')
d={}
kw=['LC1','LC2']
for input in kw:
dict(input)
When it inputs LC2 the function break right away and I'm not sure why.The end goal is to have a dictionary that looks like this当它输入LC2 时,函数立即中断,我不知道为什么。最终目标是拥有一个看起来像这样的字典
d={LC1:None,LC2:None} d={LC1:None,LC2:None}
Simple way to do it:简单的方法来做到这一点:
def todict(vals,file):
d={}
for line in file:
if line.rstrip() in vals:
d[line.rstrip()]=None
return d
file = open("Text.txt",'r')
print(todict(['LC1','LC2'],file))
But still the easiest way is:但最简单的方法仍然是:
def todict(vals,file):
return {}.fromkeys([i.rstrip() for i in file if i.rstrip() in vals])
file = open("Text.txt",'r')
print(todict(['LC1','LC2'],file))
Both reproduce:两者都重现:
{'LC1': None, 'LC2': None}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.