0

我正在使用 for 循环来读取文件,但我只想读取特定的行,比如以“af”和“apn”开头的行。是否有任何内置功能可以实现这一点?

阅读后如何拆分这一行?
如何将拆分的元素存储到字典中?
假设拆分后行的第一个元素是员工 ID,我将其存储在字典中,然后第二个元素是他的全名,我也想将其存储在字典中。
所以当我使用这一行“employee_dict{employee_ID}”时,我会得到他的全名吗?

谢谢你。

4

4 回答 4

0

你可以很容易地做到这一点

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']

希望这能给你一个关于如何去做的想法

于 2013-08-07T09:45:51.593 回答
0

如果你的文件看起来像

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']

于 2013-08-07T09:45:53.823 回答
0
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))
于 2013-08-07T10:09:12.043 回答
0
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

上面的程序将读取文件并将第二个元素存储为 id,如果它以 'af' 或 'apn' 开头,则将第三个元素存储为 name。假设逗号是分隔符。

现在您可以使用 dictOfNames[id] 来获取名称。

于 2013-08-07T14:58:21.157 回答