我需要一些帮助来了解这里发生了什么



我正在输入的CSV文件的屏幕截图

这是我正在尝试运行的代码。我正在尝试调用函数来运行程序。get_toc_tuple应该将行拆分为列。read_toc应该读取文件并将列复制到列表中。get_cell是你可以选择的选项之一。最终我希望能够使用get_work_phoneget_shiftprint_cell应该打印姓名和手机号码的正确信息
我不明白为什么这些调用函数不起作用。

它只是打印:

Team Member      Cell Phone

我的代码:

import re

def get_toc_tuple(line_str):
data = re.split(r's{2,}', line_str)

team_member = data[0]
desk_phone = data[2]
cell_phone = data[3]
shift = data[4]
return (team_member, desk_phone, cell_phone, shift)

def read_toc(filename):
fileread = open(filename, 'r')
toc_list = []
fileread.readlines()[0]
for line in fileread.readlines()[1:]:
toc_list.append(get_toc_tuple(line.strip()))

fileread.close()
return toc_list

def get_cell(toc_list):
cell_list = []
for tup in toc_list:
if name in tup[0]:
cell_list.append(tup[3])
return cell_list

def print_cell(cell_list):
print('%-19s%-1s%-13sn' % ('Team Name', ' ', 'Cell Phone'))
for line in cell_list:
team_member = line[0]
cell_phone = line[3]
print('%-19s%-1s%-13sn' % (team_member, ' ', cell_phone))

if __name__ == '__main__':
option = input("Cell Phone, Work Phone, or Shift? ")
name = input('Employee: ')
filename = input('Select a file location: ')
toc_list = read_toc(filename)   
if option == 'Cell Phone':
cell_list = get_cell(toc_list)
print_cell(cell_list)

[1]: https://i.stack.imgur.com/ZrblW.png

使用csv模块最容易解决这类问题。尝试以csv格式导出文件(使用excel或任何其他工具(:

Team Member,Title,Desk Phone,Cell Phone,Shift
Bob Smith,Technical Support,xxx-xxx-xxxx,xxx-xxx-xxx,M-F 8a-5p
Todd Wilson,Technical Support,616-233-5065,734-709-1472,M-F 8a-5p

然后使用:

import csv
rows = []
file = open("D:/team.csv")
with file:
read = csv.DictReader(file)
for row in read:
rows.append(dict(row))

执行上述代码后,rows列表将包含文件中映射在标题行项目上的行:

[{'Team Member': 'Bob Smith', 'Title': 'Technical Support', 'Desk Phone': 'xxx-xxx-xxxx', 'Cell Phone': 'xxx-xxx-xxx', 'Shift': 'M-F 8a-5p'}, {'Team Member': 'Todd Wilson', 'Title': 'Technical Support', 'Desk Phone': '616-233-5065', 'Cell Phone': '734-709-1472', 'Shift': 'M-F 8a-5p'}]

一旦你有了这个列表,就很容易解析它并提取你想要的任何信息。例如,团队成员Todd Wilson的桌面电话和轮班,将类似于:

for row in rows:
if row['Team Member'] == 'Todd Wilson':
print(row['Desk Phone'], row['Shift'])

最新更新