【问题标题】:a loop to read lines that start with specific letters读取以特定字母开头的行的循环
【发布时间】:2013-08-07 09:31:07
【问题描述】:
我正在使用 for 循环来读取文件,但我只想读取特定的行,比如以“af”和“apn”开头的行。是否有任何内置功能可以实现这一点?
这一行看完后如何分割?
如何将拆分后的元素存储到字典中?
假设拆分后行的第一个元素是员工 ID,我将其存储在字典中,然后第二个元素是他的全名,我也想将其存储在字典中。
所以当我使用这一行“employee_dict{employee_ID}”时,我会得到他的全名吗?
谢谢。
【问题讨论】:
标签:
python
loops
dictionary
readline
【解决方案1】:
你可以很容易地做到这一点
f = open('file.txt', 'r')
employee_dict = {}
for line in f:
if line.startswith("af") or line.startswith("apn"):
emprecords = line.split() #assuming the default separator is a space character
#assuming that all your records follow a common format, you can then create an employee dict
employee = {}
#the first element after the split is employee id
employee_id = int(emprecords[0])
#enter name-value pairs within the employee object - for e.g. let's say the second element after the split is the emp name, the third the age
employee['name'] = emprecords[1]
employee['age'] = emprecords[2]
#store this in the global employee_dict
employee_dict[employee_id] = employee
要在完成上述操作后检索员工 id 1 的姓名,请使用以下内容:
print employee_dict[1]['name']
希望这能给你一个关于如何去做的想法
【解决方案2】:
如果你的文件看起来像
af, 1, John
ggg, 2, Dave
你可以像这样创建字典
d = {z[1].strip() : z[2].strip() for z in [y for y in [x.split(',') for x in open(r"C:\Temp\test1.txt")] if y[0] in ('af', 'apn')]}
更易读的版本
d = {}
for l in open(r"C:\Temp\test1.txt"):
x = l.split(',')
if x[0] not in ('af', 'apn'): continue
d[x[1].strip()] = x[2].strip()
在这个例子中,两种解决方案都会给你d = {'1': 'John'}。要从字典中获取名称,您可以执行name = d['1']
【解决方案3】:
prefixes = ("af", "apn")
with open('file.txt', 'r') as f:
employee_dict = dict((line.split()[:2]) for line in f if any(line.startswith(p) for p in prefixes))
【解决方案4】:
dictOfNames={}
file = open("filename","r")
for line in file:
if line.startswith('af') or if line.startswith('apn'):
line=line.split(',') #split using delimiter of ','
dictOfNames[line[1]] = line[2] # take 2nd element of line as id and 3rd as name
如果它以'af'或'apn'开头,上面的程序将读取文件并将第二个元素存储为id,将第三个元素存储为name。假设逗号是分隔符。
现在您可以使用 dictOfNames[id] 来获取名称。