我正在尝试搜索我拥有的员工姓名的文本文件,但它似乎没有工作,但它也没有丢失任何错误。每当我在这个文件中搜索一个单词时,它都会进入get_the_info函数,但它似乎永远不会到达for循环。我假设这是因为我使用了print语句试图找出问题所在。我是编程新手,但我认为这是解决一些问题的常见惯例?无论如何,代码是:
import os
import sys
class find_employee:
def __init__(self):
self.get_the_info()
def get_the_info(self):
print "inside get info funct"
self.naples_empschedule = open("schedule.txt","r+")
self.read_schedule = self.naples_empschedule.readlines()
self.name = raw_input(" Enter your first and last name please ")
for line in self.naples_empschedule:
print " now inside for loop"
self.values = aline.split()
if self.name in line:
print ("Name:", self.values[0,1],"\n", "Position:", self.values[3],"\n", "Total Hours:", self.values[11])
else:
print ("You dont work here")
find_employee()
答案 0 :(得分:1)
self.values[0,1]
在这里,您尝试使用引发错误的元组(0,1)索引列表。而是使用
self.values[0]
或
self.values[1]
取决于您希望从列表中选择哪个项目。
答案 1 :(得分:1)
你正在混合类和功能。试试这个:
class EmployeeFinder(object):
def __init__(self, path_to_schedule, name=None):
self.name = name or raw_input("Enter your first and last name please: ")
self.path_to_schedule = path_to_schedule
def get_the_info(self):
with open(path_to_schedule, "r") as schedule_file:
for line in schedule_file:
values = line.split()
if self.name in line:
print("Name: " + values[0:1] + "\n" + \
"Position: " + self.values[3] + "\n" \
"Total Hours: ", self.values[11])
# note that this still won't work because values[0:1]
# will return a list, not a string. You might need
# ' '.join(values[0:1]).
else:
print("You don't work here")
employeefinder = EmployeeFinder("path/to/schedule/file", "Adam Smith")
employeefinder.get_the_info()
然而,看起来你可能会更好地使用一个函数,而不是试图强制对象。函数式编程并不是一件坏事。
def find_employee(path_to_schedule, name):
with open(path_to_schedule, "r") as schedule_file:
for line in schedule_file:
if name in line:
values = line.split()
new_name = ' '.join(values[0:1]) # I'm guessing at your intent
position = values[3]
hours = values[11]
print("Name: {}\nPosition: {}\nTotal Hours: {}".format(
new_name, position, hours))
(我的上一个例子使用string formatting,这是一个比字符串连接更好的解决方案)
答案 2 :(得分:0)
我认为你的for line in self.naples_empschedule:
应为for line in self.read_schedule:
。