【贪心学院】python学习笔记

预习课第二章

知识点
在这里插入图片描述
作业
在这里插入图片描述
在这里插入图片描述

first_num=input("请输入第一个数字:")
operation=input("请输入运算符:")
second_num=input("请输入第二个数字:")
#判断输入数字为整型或浮点型
if '.' in first_num:
    first_num=float(first_num)
else:
    first_num=int(first_num)
if '.' in second_num:
    second_num=float(second_num)
else:
    second_num=int(second_num)
#基本运算符
if operation=='+':
    result=first_num+second_num
elif operation=='-':
    result=first_num-second_num
elif operation=='*':
    result=first_num*second_num
elif operation=='/':
    result=first_num/second_num
#算数运算符
elif operation=='**':#幂运算
    result=first_num**second_num
elif operation=="//":#取整除运算
    result=first_num//second_num
elif operation=='%':#取模运算
    result=first_num%second_num
#赋值运算符
elif operation=='+=':
    first_num += second_num
    result = first_num
elif operation=='-=':
    first_num -= second_num
    result = first_num
elif operation=='*=':
    first_num *= second_num
    result = first_num
elif operation=="/=":
    first_num /= second_num
    result = first_num
elif operation=='%=':
    first_num %= second_num
    result = first_num
elif operation=='**=':
    first_num **= second_num
    result = first_num
elif operation=="//=":
    first_num//=second_num
    result=first_num
else:
    print("运算符错误!")
    exit()
print("计算结果为:"+str(result))

预习课第三章

知识点

  • 怎么学习python3的官方文档
    在这里插入图片描述
python3 -m pydoc -p 8888
  • 冒泡排序
#冒泡冒泡,最大的泡一直往上(右)走
#冒泡排序,每一次外部循环,将一个最大值排到最后。
l1=[2,3,4,1,5,6,7,9,8]
for i in range(len(l1)-1):#第一次外部循环结束,将最大值排到最后,以此类推。
    for j in range(len(l1)-1-i):#一次内部循环,对两个相邻的数进行比较
        if l1[j+1]<l1[j]:
            temp=l1[j]
            l1[j]=l1[j+1]
            l1[j+1]=temp
print(l1)
  • python的工程结构
    在这里插入图片描述
  • 命名规则
    在这里插入图片描述

作业
在这里插入图片描述

#从大到小冒泡排序
l1=[2,3,4,1,5,6,7,9,8]
m=len(l1)-1
for i in range(len(l1)-1):
    for j in range(len(l1)-1-i):
        if l1[m-j]>l1[m-j-1]:
            temp=l1[m-j]
            l1[m-j]=l1[m-j-1]
            l1[m-j-1]=temp
#插入数据,保持顺序
data=input("请输入一个数字:")
if '.' in data:
    data=float(data)
else:
    data=int(data)
for i in l1:
    if i<data:
        index=l1.index(i)
        l1.insert(index,data)
        break
print(l1)

在这里插入图片描述

#列表排序
l=[4,6,7,9,11,2,90,44]
for i in range(len(l)-1):
    for j in range(len(l)-i-1):
        if l[j+1]<l[j]:
            temp=l[j]
            l[j]=l[j+1]
            l[j+1]=temp
print((l))
#对半查找
data=input("please give me your number:")
if ('.' in data) or (int(data) not in l):
    print("-1")
    exit()
else:
    data=int(data)
index =[]
def find(l,data):
    global index
    m_value=int(len(l)/2)
    if data<l[m_value]:
        l=l[:m_value]
        find(l,data)
    elif data>l[m_value]:       
        index.append(m_value)
        l=l[m_value:]
        find(l,data)
    else:
        print(m_value+sum(index))#data在列表中的index
        return m_value
find(l,data)

预习课第五章

知识点

  • 正则表达式
    在这里插入图片描述

作业
在这里插入图片描述

import re
def check_email(email):
    reg="(^[0-9a-zA-Z]+@163.com)|(^[0-9a-zA-Z]+@sina.com)|(^[0-9a-zA-Z]+@sina.com.cn)|(^[0-9a-zA-Z]+@126.com)"
    result=re.findall(reg,email)
    print(result)
    if result:
        print("find it!")
        return True
    else:
        print("none")
        return False
email1="15209876354@163.com"
email2="A123@sina.com"
email3="_2134891@sina.com.cn"
email4="213441@sina.com.cn"
check_email(email1)
check_email(email2)
check_email(email3)
check_email(email4)

Python之Scrapy遇见个坑

  • stock.py
# -*- coding: utf-8 -*-
import scrapy
from urllib import parse
import re
from stock_project.items import StockItem
class StockSpider(scrapy.Spider):
    name = 'stock'
    allowed_domains = ['pycs.greedyai.com/']
    start_urls = ['http://pycs.greedyai.com/']

    def parse(self, response):
        post_urls=response.xpath("//*/a/@href").extract()
        for post_url in post_urls:
            yield scrapy.Request(url=parse.urljoin(response.url,post_url),callback=self.parse_detail,dont_filter=True)


    def parse_detail(self,response):
        stock_item=StockItem()
        #董事会成员姓名
        stock_item["names"]=self.get_tc(response)
        #成员性别
        stock_item["sexes"]=self.get_sex(response)
        #成员年龄
        stock_item["ages"]=self.get_age(response)
        #成员职位
        stock_item["leaders"]=self.get_leader(response,len(stock_item["names"]))
        #股票代码
        stock_item["codes"]=self.get_code(response)
        yield stock_item

    def get_tc(self,response):
        names=response.xpath("//*[@class=\"tc name\"]/a/text()").extract()
        return names
    def get_leader(self,response,length):
        leaders= response.xpath("//*[@class=\"tl\"]/text()").extract()
        leaders=leaders[0:length]
        return  leaders
    def get_sex(self,response):
        sexes=response.xpath("//*[@class=\"intro\"]/text()").extract()
        sex_list=[]
        for sex in sexes:
            try:
                res = "[男|女]"
                temp=re.findall(res,sex)[0]
            except(IndexError):
                continue
            sex_list.append(temp)
        return sex_list
    def get_age(self,response):
        ages = response.xpath("//*[@class=\"intro\"]/text()").extract()
        age_list = []
        for age in ages:
            try:
                res="\d+"
                temp = re.findall(res, age)[0]
            except(IndexError):
                continue
            age_list.append(temp)
        return age_list
    def get_code(self,response):
        code=response.xpath("/html/body/div[3]/div[1]/div[2]/div[1]/h1/a/@title").extract()
        return code[0]
  • piplines.py
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os

class StockProjectPipeline(object):
    def process_item(self, item, spider):
        return item

class StockPipeline(object):
    def process_item(self, item, spider):
        self.file=open("executive_prev.csv","a+")
        if os.path.getsize("executive_prev.csv"):
            self.write_content(item)
        else:
            self.file.write("高管姓名,性别,年龄,股票,职位\n")
        self.file.flush()
    def write_content(self,item):
        names=item["names"]
        sexes=item["sexes"]
        ages=item["ages"]
        code=item["codes"]
        leaders=item["leaders"]
        for i in range(len(names)):
            m1, m2, m3, m4, m5 = len(names), len(sexes), len(ages), len(code), len(leaders)
            print(m1, m2, m3, m4, m5)
            result=names[i]+','+sexes[i]+','+ages[i]+','+code+','+leaders[i]+'\n'
            self.file.write(result)


        return item
  • items.py
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class StockProjectItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    pass

class StockItem(scrapy.Item):
    names = scrapy.Field()
    sexes = scrapy.Field()
    ages = scrapy.Field()
    leaders = scrapy.Field()
    codes = scrapy.Field()
  • settings.py
# -*- coding: utf-8 -*-

# Scrapy settings for stock_project project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'stock_project'

SPIDER_MODULES = ['stock_project.spiders']
NEWSPIDER_MODULE = 'stock_project.spiders'

ITEM_PIPELINES = {
    'stock_project.pipelines.StockProjectPipeline': 300,'stock_project.pipelines.StockPipeline':1,
}

最终作业

项目目标: 利用爬虫爬取的数据来搭建一个小型的证券知识图谱

数据源:本项目需要用到两种数据源:一种是公司董事的信息,另一种是股票的行业以及概念信息。

- 公司董事的信息:这部分数据是你应该在爬虫课程中已经完成的部分,最后生成一个executive_prep.csv文件

格式如下:

高管姓名、性别、年龄、股票代码、职位

朴明志,    男,   5160007,  董事长、董事

高燕,       女,   60600007, 执行董事

刘永政,    男,   50600008, 董事长、  董事

- 股票行业以及概念信息: 这部分信息也可以通过网上公开的信息得到。在这里,我们使用Tushare工具来获得,详细细节见之后具体的任务部分。 

- 知识图谱结构设计: 具体设计文件叫做design.png,该文件可在资料区下载。
........................
任务1: 获取股票行业和概念的信息。

对于这部分信息,我们可以利用Tushare工具来获取,官网为 http://tushare.org/index.html,并可以从官网下载Tushare工具包。 下载完之后,在python里即可以调用股票行业和概念信息。

通过以下的代码即可以获得股票行业信息,并把返回的信息直接存储在 “stock_industry_prep.csv”文件里。http://tushare.org/classifying.html#id2

import tushare as ts

df = ts.get_industry_classified()

// TODO 保存成"stock_industry_prep.csv"

类似的,可以通过以下的代码即可以获得股票概念信息,并把它们存储在 “stock_concept_prep.csv”文件里。

df = ts.get_concept_classified()

//  TODO 保存成“stock_concept_prep.csv”


任务2: 创建可以导入Neo4j的.csv文件

在前一个任务里,我们已经分别生成了 “executive_prep.csv”, "stock_industry_prep.csv", "stock_concept_prep.csv",  但这个文件不能直接导入到Neo4j数据库。所以需要做一些处理,并生成能够直接导入Neo4j的.csv格式。

我们需要生成这几个文件: “executive.csv”, "stock.csv", "concept.csv", "industry.csv", "executive_stock.csv", "stock_industry.csv", "stock_concept.csv"。

对于格式的要求,请参考:https://neo4j.com/docs/operations-manual/current/tutorial/import-tool/

 
任务3: 下载并安装neo4j数据库

下载地址:https://neo4j.com/download/other-releases/#releases

解压后,启动服务:bin/neo4j start

初始用户名/密码neo4j/neo4j,按照提示修改密码

 
任务4: 创建可以导入Neo4j的.csv文件

在前两个任务里,我们已经分别生成了 “executive_prep.csv”, "stock_industry_prep.csv", "stock_concept_prep.csv",  但这个文件不能直接导入到Neo4j数据库。所以需要做一些处理,并生成能够直接导入Neo4j的.csv格式。

我们需要生成这几个文件: “executive.csv”, "stock.csv", "concept.csv", "industry.csv", "executive_stock.csv", "stock_industry.csv", "stock_concept.csv"。

对于格式的要求,请参考:https://neo4j.com/docs/operations-manual/current/tutorial/import-tool/

(尽量阅读neo4j官网,这样可以提高自己的学习能力,如果有问题的同学,可以在资料区中下载标准的数据格式) 
 

任务5: 利用上面的csv文件生成数据库

bin/neo4j-admin import --nodes executive.csv --nodes stock.csv --nodes  concept.csv --nodes industry.csv  --relationships executive_stock.csv --relationships stock_industry.csv --relationships stock_concept.csv

这个命令会把所有的数据导入到Neo4j中,数据默认存放在 graph.db 文件夹里。如果graph.db文件夹之前已经有数据存在,则可以选择先删除再执行命令。 

把Neo4j服务重启之后,就可以通过 localhost:7474 观察到知识图谱了。 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

immortal12

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值