Python-金融相关代码讲解

文章目录

概要

简单代码

主要是讲解一下如何理解,构建自己的代码思维,以便更好使用AI和自己的智慧制作代码

整体架构流程

先放上代码

1.代码部分

python 复制代码
# -*- coding: utf-8 -*-

import xlwt  
import os 

def matchKeyWords(txt_folder, keyWords):
    files = os.listdir(txt_folder)  
    words_num = []
    for file in files:  
        if os.path.splitext(file)[-1] == ".txt": 
            txt_path = os.path.join(txt_folder, file)  
            with open(txt_path, "r", encoding='utf-8', errors='ignore') as fp:  
                text = fp.readlines()  
                word_freq = {}  
                for word in keyWords:  
                    num = sum(line.count(word) for line in text)  
                    word_freq[word] = num  
                    stock_code, stock_name = file.split("-", 1)  
                    year = "未知" 
                    words_num.append((word_freq, stock_code, stock_name, year))  
        return words_num 

txt_folder = "F:\\上市公司数据\\2023年报"
keyWords = ["数字化", "数据", "数据要素", "智能化"]  
words_num = matchKeyWords(txt_folder, keyWords) 
book = xlwt.Workbook(encoding='utf-8', style_overwrite_ok=True)  
sheet = book.add_sheet('关键词', cell_overwrite_ok=True)  
sheet.write(0, 0, '股票代码')  
sheet.write(0, 1, '股票名称')  
sheet.write(0, 2, '年份')  
sheet.write(0, 3, '数字化')  
sheet.write(0, 4, '数据')  
sheet.write(0, 5, '数据要素')  
sheet.write(0, 6, '智能化')
sheet.write(0, 6, '数字经济') 
for index, one in enumerate(words_num, start=1):  
    word_f, stock_code, stock_name, year = one  
    sheet.write(index, 0, stock_code)  
    sheet.write(index, 1, stock_name)  
    sheet.write(index, 2, year)  
    sheet.write(index, 3, word_f.get('数字化', 0))  
    sheet.write(index, 4, word_f.get('数据', 0))  
    sheet.write(index, 5, word_f.get('数据要素', 0))  
    sheet.write(index, 6, word_f.get('智能化', 0))  
    
book.save('keywords.xls')

对代码分,部分来看

2.逐个讲解

1)# -*- coding: utf-8 -*-

用于指定Python源文件的编码格式为UTF-8。这样可以确保源文件中的非ASCII字符(例如中文字符)能够被正确解释和显示。这在处理多语言文本或包含特殊字符的文件时特别重要。

2)基本库引入
python 复制代码
import xlwt  
import os 
  • xlwt: 用于创建和操作 Excel 文件。
  • os: 用于处理文件和目录路径。
3)函数模块

def function(参数1,参数2......):

这个函数 matchKeyWords 的作用是统计给定文件夹中的每个文本文件中指定关键词的出现频率,并返回包含这些统计结果的列表。具体步骤如下:

  1. 获取文件列表

    python 复制代码
    files = os.listdir(txt_folder)

    获取指定文件夹(txt_folder)中的所有文件和文件夹名称。

  2. 初始化存储变量

    python 复制代码
    words_num = []

    初始化一个空列表 words_num,用于存储每个文件中关键词的统计结果。

  3. 遍历文件

    python 复制代码
    for file in files:
        if os.path.splitext(file)[-1] == ".txt":

    遍历文件夹中的所有文件,并筛选出扩展名为 .txt 的文本文件。

    • os.path.splitext 是 Python os 模块中的一个函数,用于将文件路径拆分成两部分:文件名和扩展名。
    • file 是一个字符串,表示文件的路径或名称。
    • 这个函数返回一个元组 (root, ext),其中 root 是文件名,ext 是文件扩展名。
  4. 读取文件内容

    python 复制代码
    txt_path = os.path.join(txt_folder, file)
    with open(txt_path, "r", encoding='utf-8', errors='ignore') as fp:
        text = fp.readlines()

    构建每个文本文件的完整路径,并以 UTF-8 编码读取文件内容。

  5. 初始化词频字典

    python 复制代码
    word_freq = {}

    初始化一个空字典 word_freq,用于存储每个关键词在当前文件中的出现频率。

  6. 统计关键词出现频率

    python 复制代码
    for word in keyWords:
        num = sum(line.count(word) for line in text)
        word_freq[word] = num

    遍历关键词列表 keyWords,统计每个关键词在文件中每一行出现的次数,并将结果存储在 word_freq 字典中。

  7. 提取文件信息

    python 复制代码
    stock_code, stock_name = file.split("-", 1)
    year = "未知"

    假设文件名格式为 股票代码-股票名称.txt,通过 split 方法分割文件名,提取股票代码和股票名称。年份暂时设置为 "未知"。

  8. 存储统计结果

    python 复制代码
    words_num.append((word_freq, stock_code, stock_name, year))

    将统计结果(词频字典、股票代码、股票名称、年份)作为一个元组添加到 words_num 列表中。

words_num 是一个列表,其中的每个元素都是一个元组,包含四个部分:词频字典、股票代码、股票名称和年份。它大概长这样:

python 复制代码
words_num = [
    (
        {'数字化': 10, '数据': 15, '数据要素': 5, '智能化': 8},  # 词频字典
        '600519',  # 股票代码
        '贵州茅台',  # 股票名称
        '未知'  # 年份
    ),
    (
        {'数字化': 7, '数据': 20, '数据要素': 10, '智能化': 3},
        '000858',
        '五粮液',
        '未知'
    ),
    # 更多的元组
]

其中,词频字典记录了每个关键词在对应文本文件中出现的次数,股票代码和股票名称分别从文件名中提取,年份在示例中暂时设置为 "未知"。

最后return是函数返回一个结果,返回包含所有文件统计结果的列表 words_num

4)主程序
python 复制代码
txt_folder = "F:\\上市公司数据\\2023年报"
keyWords = ["数字化", "数据", "数据要素", "智能化"]
words_num = matchKeyWords(txt_folder, keyWords)
book = xlwt.Workbook(encoding='utf-8', style_overwrite_ok=True)
  1. txt_folder = "F:\\上市公司数据\\2023年报":定义了变量 txt_folder,其值为包含文本文件的文件夹路径。
  2. keyWords = ["数字化", "数据", "数据要素", "智能化"]:定义了变量 keyWords,其值为一个关键词列表,这些关键词将在文本文件中进行匹配统计。
  3. words_num = matchKeyWords(txt_folder, keyWords):调用 matchKeyWords 函数,传入 txt_folderkeyWords 两个参数。函数将返回一个包含统计结果的列表,并将其赋值给 words_num 变量。
  4. book = xlwt.Workbook(encoding='utf-8', style_overwrite_ok=True):使用 xlwt 模块创建一个新的 Excel 工作簿对象,并设置编码为 UTF-8。

这段代码的功能是创建一个新的 Excel 工作表,并在表格的第一行(即表头)写入相关的列标题。

具体解释如下:

python 复制代码
sheet = book.add_sheet('关键词', cell_overwrite_ok=True)
  • 使用 book.add_sheet('关键词', cell_overwrite_ok=True) 创建了一个名为"关键词"的新的工作表对象。参数 cell_overwrite_ok=True 表示允许覆盖单元格中的现有内容。
python 复制代码
sheet.write(0, 0, '股票代码')
sheet.write(0, 1, '股票名称')
sheet.write(0, 2, '年份')
sheet.write(0, 3, '数字化')
sheet.write(0, 4, '数据')
sheet.write(0, 5, '数据要素')
sheet.write(0, 6, '智能化')
# sheet.write(0, 6, '数字经济') 
  • sheet.write(行, 列, 内容) 方法用于在指定的单元格中写入内容。

总结:这段代码的目的是初始化 Excel 表格的表头,但最后一行 sheet.write(0, 6, '数字经济') 存在覆盖问题,应当修正。

接下来的for循环

这段代码的作用是将关键词匹配的结果写入到一个 Excel 文件中。具体步骤如下:

  1. 遍历 words_num 列表

    python 复制代码
    for index, one in enumerate(words_num, start=1):
    • enumerate(words_num, start=1):将 words_num 列表中的每个元素与其索引一起返回,索引从 1 开始。
    • index 是当前迭代的索引,one 是包含关键词频率、股票代码、股票名称以及年份的元组。
  2. 解包元组

    python 复制代码
    word_f, stock_code, stock_name, year = one
    • 将元组 one 中的值分别赋给 word_f(词频字典)、stock_code(股票代码)、stock_name(股票名称)和 year(年份)。
  3. 将数据写入 Excel 表格

    python 复制代码
    sheet.write(index, 0, stock_code)
    sheet.write(index, 1, stock_name)
    sheet.write(index, 2, year)
    sheet.write(index, 3, word_f.get('数字化', 0))
    sheet.write(index, 4, word_f.get('数据', 0))
    sheet.write(index, 5, word_f.get('数据要素', 0))
    sheet.write(index, 6, word_f.get('智能化', 0))
    • sheet.write(行, 列, 内容) 方法用于在指定的单元格中写入内容。
    • stock_code 写入当前行的第 0 列。
    • stock_name 写入当前行的第 1 列。
    • year 写入当前行的第 2 列。
    • 使用 word_f.get('关键词', 默认值) 获取关键词的频率,如果关键词不存在,则使用默认值 0。
    • 分别将 数字化数据数据要素智能化 的词频写入当前行的第 3 到第 6 列。
  4. 保存 Excel 文件

    python 复制代码
    book.save('keywords.xls')
    • 将创建好的 Excel 工作簿保存为 keywords.xls 文件。

总结:这段代码的主要目的是将关键词匹配的结果写入到一个 Excel 文件中,方便后续查看和分析。

小结

小结喔

这段代码是一个极具实用价值的文本分析工具,特别适合零基础开发者学习。它用不到50行代码完成了文件处理、关键词统计、数据整理到Excel导出的完整流程,堪称自动化办公的典范。以下是代码小白最值得吸收的精华:

1. 问题拆解思维

代码将复杂任务拆解为清晰步骤:

遍历文件夹→读取文本→统计词频→提取文件名信息→结构化存储→Excel输出。

这种分而治之的思维方式,是解决编程问题的金钥匙。

2. 文件处理三件套

(os.listdir/os.path.splitext/os.path.join)教会你:

如何批量获取文件列表

精准识别文件类型

安全构建文件路径

这些是自动化处理海量文件的基础功。

3. 字典的妙用:

通过word_freq字典实现关键词计数,展示了用键值对管理数据的艺术。这种数据结构在数据分析中至关重要。

4. 上下文管理器(with open...)

是文件操作的最佳实践,它能自动处理资源释放,避免内存泄漏,体现了Python的优雅特性。

5. 数据标准化输出:

将结果统一为(stock_code, stock_name, year, counts)的元组结构,这种规范化思维是数据清洗的核心。

6. Excel自动化:

通过xlwt库实现:

工作簿/工作表创建

表头设计

动态数据填充

这是办公自动化的必备技能,可节省大量手工操作时间。

这段代码的价值远超其实现功能本身------它示范了如何用编程思维将重复性工作自动化。记住:优秀开发者不是写代码的人,而是用代码解决问题的人。每当你发现自己在重复操作文件/数据时,就是该祭出这类自动化脚本的时刻!

相关推荐
rookie fish27 分钟前
websocket结合promise的通信协议
javascript·python·websocket·网络协议
Heorine28 分钟前
数学建模 绘图 图表 可视化(3)
python·数据可视化
2301_7644413336 分钟前
基于BERT的序列到序列(Seq2Seq)模型,生成文本摘要或标题
人工智能·python·深度学习·bert
网络风云43 分钟前
Flask(二)项目结构与环境配置
后端·python·flask
Doker 多克1 小时前
Python Django系列—多数据库
python·django
蹦蹦跳跳真可爱5891 小时前
Python----计算机视觉处理(Opencv:霍夫变换)
人工智能·python·opencv·计算机视觉
5967851541 小时前
C#重写treeView控件
java·c#
程序员柒叔2 小时前
制作PaddleOCR/PaddleHub的Docker镜像
python·docker·ocr·paddle
喜欢理工科2 小时前
18 C语言标准头文件
c语言·python·算法·c语言标准头文件