Python 在文本文件中搜索不起作用且未抛出任何错误的单词
我试图搜索一个文本文件,我有一个员工的名字,它似乎不工作,但它也没有抛出任何错误。每当我在这个文件中搜索一个单词时,它都会进入get_the_info函数,但似乎从未到达for循环。我之所以这样认为是因为我用打印语句试图找出问题所在。我是编程新手,但我认为这是解决一些问题的常见惯例?无论如何,代码如下:Python 在文本文件中搜索不起作用且未抛出任何错误的单词,python,class,python-2.7,Python,Class,Python 2.7,我试图搜索一个文本文件,我有一个员工的名字,它似乎不工作,但它也没有抛出任何错误。每当我在这个文件中搜索一个单词时,它都会进入get_the_info函数,但似乎从未到达for循环。我之所以这样认为是因为我用打印语句试图找出问题所在。我是编程新手,但我认为这是解决一些问题的常见惯例?无论如何,代码如下: import os import sys class find_employee: def __init__(self): self.get_the_info()
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()
我认为你的
是在赛尔夫。那不勒斯的时间表:
对于self中的行,应为。请阅读计划:
self.values[0,1]
在这里,您试图用一个元组(0,1)索引一个列表,该元组会抛出一个错误。改用
self.values[0]
或
取决于您希望从列表中选择哪一项。您正在混合类和函数。请尝试以下方法:
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))
(我的上一个示例使用了比字符串串联更好的解决方案)这实际上不会改变任何东西。文件对象是可编辑的(也就是说,
对于fileobj中的行
相当于对于fileobj中的行。readlines()
)感谢这对我的帮助:)
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))