|
发表于 2024-2-4 20:34:47
|
显示全部楼层
解决方案(未经测试)
AI生成代码
这个脚本现在能处理用户输入,但格式必须遵循约定(例如使用'r'前缀来指定行操作,使用'c'前缀来指定列操作),并且指示列时使用Excel中的列名(例如"A", "B", "C"等)。
在实际使用中,你可能需要根据Excel文件的实际情况进一步调整代码,以支持不同的列名或其他特定格式。同样,错误处理仍然是简化版;
在生产环境中,你需要确保你的代码能处理不同类型的错误,异常情况以及提供友好的用户反馈。
- import pandas as pd
- def parse_user_input(user_input):
- # 假设用户输入格式 'filename.xls:Sheet1:r1,2,3+4,5;cA,B+D,E'
- instructions = []
- items = user_input.split(';')
- for item in items:
- parts = item.split(':', 2)
- if len(parts) < 3:
- print("Invalid input format.")
- return None
- filename, sheet, indices = parts
- if indices.startswith('r'): # Row input
- rows = [list(map(int, r.split(','))) for r in indices[1:].split('+')]
- instructions.append({'file': filename, 'sheet': sheet, 'rows': rows})
- elif indices.startswith('c'): # Column input
- cols = [c.split(',') for c in indices[1:].split('+')]
- instructions.append({'file': filename, 'sheet': sheet, 'cols': cols})
- return instructions
- def calculate_and_compare(df, rows=None, cols=None):
- if rows:
- row_indices = [r-1 for r in rows] # Convert to 0-based index
- sum1 = df.iloc[row_indices].sum().sum()
- return sum1
- elif cols: # Column input
- sums = [df[col].sum() for col in cols] # Sum each specified column
- return sums
- def execute_instructions(instructions):
- for instr in instructions:
- df = pd.read_excel(instr['file'], sheet_name=instr['sheet'])
- # 执行行的计算并比较结果
- if 'rows' in instr:
- for i in range(len(instr['rows'])):
- result = calculate_and_compare(df, rows=instr['rows'][i])
- print(f"File: {instr['file']}, Sheet: {instr['sheet']}, Rows: {instr['rows'][i]}, Sum: {result}")
- # 执行列的计算并比较结果
- if 'cols' in instr:
- for i in range(len(instr['cols'])):
- result = calculate_and_compare(df, cols=instr['cols'][i])
- print(f"File: {instr['file']}, Sheet: {instr['sheet']}, Columns: {instr['cols'][i]}, Sums: {result}")
- def main():
- user_input = input("Please input the instructions:(example: 'filename.xls:Sheet1:r1,2,3+4,5;cA,B+D,E')\n")
- instructions = parse_user_input(user_input)
- if instructions is None:
- return
- # 执行指令
- execute_instructions(instructions)
- if __name__ == "__main__":
- main()
复制代码
求最佳
|
|