利用pandas库改写import xlrd def main(): # 打开Excel文件 excel_file = xlrd.open_workbook('C:\\Users\\fang\\Desktop\\Python\\2022蓝桥江西省赛.xls') # 获取工作表 sheet = excel_file.sheet_by_name('Sheet1') # 获取行数 rows = sheet.nrows # 初始化一个字典,用来记录每个比赛科目的获奖情况 subject_awards = {} # 循环遍历每行数据,统计每个比赛科目的获奖情况 for i in range(1, rows): # 从第二行开始遍历,忽略表头 if sheet.cell(i, 2).value == '江西理工大学': subject = sheet.cell(i, 4).value.strip() award = sheet.cell(i, 5).value if subject not in subject_awards: subject_awards[subject] = {'一等奖': 0, '二等奖': 0, '三等奖': 0} if award in subject_awards[subject]: subject_awards[subject][award] += 1 # 将结果写入文件 with open('C:\\Users\\fang\\Desktop\\Python\\result2.txt', 'w', encoding='utf8') as file: for subject in subject_awards: file.write('{}:\n'.format(subject)) for award in subject_awards[subject]: file.write('\t{}:{}\n'.format(award, subject_awards[subject][award])) file.write('\n') main()
时间: 2024-02-04 17:01:51 浏览: 99
Read data from the Excel spreadsheet.zip_Spreadsheet::Read_excel
可以使用pandas库中的read_excel函数来读取Excel文件,具体改写如下:
```python
import pandas as pd
def main():
# 读取Excel文件
excel_file = pd.read_excel('C:\\Users\\fang\\Desktop\\Python\\2022蓝桥江西省赛.xls', sheet_name='Sheet1')
# 获取行数
rows = excel_file.shape[0]
# 初始化一个字典,用来记录每个比赛科目的获奖情况
subject_awards = {}
# 循环遍历每行数据,统计每个比赛科目的获奖情况
for i in range(0, rows):
if excel_file.iloc[i, 2] == '江西理工大学':
subject = excel_file.iloc[i, 4].strip()
award = excel_file.iloc[i, 5]
if subject not in subject_awards:
subject_awards[subject] = {'一等奖': 0, '二等奖': 0, '三等奖': 0}
if award in subject_awards[subject]:
subject_awards[subject][award] += 1
# 将结果写入文件
with open('C:\\Users\\fang\\Desktop\\Python\\result2.txt', 'w', encoding='utf8') as file:
for subject in subject_awards:
file.write('{}:\n'.format(subject))
for award in subject_awards[subject]:
file.write('\t{}:{}\n'.format(award, subject_awards[subject][award]))
file.write('\n')
main()
```
这样就可以使用pandas库中的函数来读取Excel文件,不需要再使用xlrd库。
阅读全文