需求:实现提取指定公司后30条股票数据的Python函数
实现股票数据提取函数
openfile(file_name, company_name) 我正在构建一个股票分析程序,现有一个包含公司名称及后续大量股票数据的文本文件。需要实现名为openfile(file_name, company_name)的Python函数,功能如下:
- 打开指定txt文件并读取内容
- 找到指定公司名(如"Apple")后,返回包含其后30条数据的字典(键为日期,值为对应股价)
示例数据
02-09-26 4.12 02-09-27 3.92 02-09-30 3.37 Apple 02-08-01 7.15 02-08-02 6.72 02-08-05 5.56 02-08-06 5.49 02-08-07 5.63
预期返回格式
字典格式,键为日期字符串,值为浮点型股价,示例:
{"02-08-01": 7.15, "02-08-02": 6.72, ...}
现有代码片段
def openfile(file_name, company_name): file_words = [] with open(file_name, "r") as file: for line in file:
完整实现方案
基于现有代码,补充逻辑完成函数功能,核心思路是标记目标公司位置,然后收集后续最多30条有效数据:
def openfile(file_name, company_name): stock_data = {} found_company = False collected_count = 0 with open(file_name, "r") as file: for line in file: # 去除首尾空白,跳过空行 cleaned_line = line.strip() if not cleaned_line: continue # 未找到目标公司时,检查当前行是否匹配 if not found_company: if cleaned_line == company_name: found_company = True else: # 已找到公司,开始收集数据,最多30条 if collected_count >= 30: break # 分割日期与股价,兼容多空格/制表符分隔 line_parts = cleaned_line.split() if len(line_parts) == 2: date, price_str = line_parts # 尝试转换股价为浮点型,跳过格式错误的行 try: stock_data[date] = float(price_str) collected_count += 1 except ValueError: continue return stock_data
代码说明
found_company:布尔标记,确认是否已定位到目标公司的行collected_count:计数器,控制最多收集30条有效数据- 用
strip()处理每行首尾空白,避免空行或多余空格干扰判断 split()自动处理多空格/制表符的分隔场景,兼容不同格式的文本行- 加入
try-except捕获股价转换失败的情况,跳过无效数据行 - 收集满30条后直接跳出循环,减少不必要的文件读取操作
内容的提问来源于stack exchange,提问作者Wysra
相关产品推荐
相关产品推荐

