在OpenCV中,我们可以使用cv2.line(), cv2.rectangle(), cv2.circle(), cv2.ellipse(), cv2.polylines()等函数来绘制各种图形。

下面是这些函数的基本用法:

  1. 直线绘制:cv2.line()



import cv2
import numpy as np
 
img = np.zeros((512,512,3), np.uint8)
cv2.line(img,(0,0),(511,511),(255,0,0),5)
  1. 矩形绘制:cv2.rectangle()



import cv2
import numpy as np
 
img = np.zeros((512,512,3), np.uint8)
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
  1. 圆形绘制:cv2.circle()



import cv2
import numpy as np
 
img = np.zeros((512,512,3), np.uint8)
cv2.circle(img,(447,63), 63, (0,0,255), -1)
  1. 椭圆绘制:cv2.ellipse()



import cv2
import numpy as np
 
img = np.zeros((512,512,3), np.uint8)
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)
  1. 多边形绘制:cv2.polylines()



import cv2
import numpy as np
 
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2))
 
img = np.zeros((512,512,1), np.uint8)
cv2.polylines(img,[pts],True,(255,255,255),2)

以上代码中,我们首先创建了一个空白的图像,然后调用相应的绘图函数在图像上绘制了我们需要的图形。这些函数的参数可能会有所不同,但是大部分都遵循以下模式:




cv2.function(image, start_point, end_point, color, thickness)

其中,

  • image:要绘制图形的图像
  • start\_point:图形的起始点
  • end\_point:图形的结束点
  • color:图形的颜色,以(B, G, R)的格式给出
  • thickness:线的粗细,如果为负值(如-1),则表示要绘制实心图形

注意:在使用这些函数时,确保你的numpy数组是uint8类型,这样才能正确地显示颜色。

Python操作Elasticsearch可以使用elasticsearch包,它是一个Python客户端,可以与Elasticsearch集群交互。

安装:




pip install elasticsearch

基本操作:




from elasticsearch import Elasticsearch
 
# 连接到Elasticsearch
es = Elasticsearch("http://localhost:9200")
 
# 创建/更新文档
es.index(index="myindex", id=1, document={"name": "John", "age": 30})
 
# 获取文档
result = es.get(index="myindex", id=1)
 
# 搜索文档
response = es.search(index="myindex", query={"match": {"name": "John"}})
 
# 删除文档
es.delete(index="myindex", id=1)

以上是使用elasticsearch包进行基本操作的示例。更高级的操作如使用更复杂的查询、批量操作、脚本操作等也都可以通过这个包来完成。

在OpenCV中,我们可以使用cv2.line(), cv2.rectangle(), cv2.circle(), cv2.ellipse()等函数来绘制不同的图形。

下面是这些函数的基本用法:

  1. cv2.line():用于绘制直线。



cv2.line(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)

参数:

  • img:要绘制的图像
  • pt1:直线起点
  • pt2:直线终点
  • color:直线颜色,以BGR格式(即蓝、绿、红)表示
  • thickness:直线宽度。如果是正数,表示宽度。如果是负数,表示此线是填充线,即将起点和终点相连,形成一个填充的矩形。
  • lineType:线型,可以是cv2.LINE\_8, cv2.LINE\_4, cv2.LINE\_AA等
  • shift:对点坐标中的小数位数

例子:




import cv2
import numpy as np
 
# 创建一张黑色背景的图片
img = np.zeros((512,512,3), np.uint8)
 
# 定义直线的起点和终点
pt1 = (0,0)
pt2 = (511,511)
 
# 直线颜色,蓝色
color = (255,0,0)
 
# 直线宽度
thickness = 2
 
# 绘制直线
cv2.line(img, pt1, pt2, color, thickness)
 
# 展示图片
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
  1. cv2.rectangle():用于绘制矩形。



cv2.rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)

参数:

  • img:要绘制的图像
  • pt1:矩形左上角点
  • pt2:矩形右下角点
  • color:矩形颜色
  • thickness:矩形边界宽度。如果是正数,表示宽度。如果是负数,表示此矩形是填充的。

例子:




import cv2
import numpy as np
 
# 创建一张黑色背景的图片
img = np.zeros((512,512,3), np.uint8)
 
# 定义矩形的左上角和右下角点
pt1 = (50,50)
pt2 = (200,200)
 
# 矩形颜色,绿色
color = (0,255,0)
 
# 矩形边界宽度
thickness = 2
 
# 绘制矩形
cv2.rectangle(img, pt1, pt2, color, thickness)
 
# 展示图片
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
  1. cv2.circle():用于绘制圆形。



cv2.circle(img, center, radius, color, thickness=None, lineType=None, shift=None)

参数:

  • img:要绘制的图像
  • center:圆心点
  • radius:圆的半径
  • color:圆的颜色
  • thickness:如果是正数,表示圆的边界宽度。如果是负数,表示圆是填充的。

例子:




import cv2
import numpy as np
 
# 创建一张黑色背景的图片
img = np.zeros((512,512,3), np.uint8)
 
# 定义圆的中心点和半径
center = (250,250)
radius = 50
 
# 圆的颜色
2024-08-25



import requests
from bs4 import BeautifulSoup
 
def get_html(url):
    """
    获取网页的HTML内容
    :param url: 网页的URL
    :return: HTML内容
    """
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        else:
            return None
    except requests.RequestException:
        return None
 
def parse_html(html):
    """
    解析HTML内容,提取需要的信息
    :param html: 网页的HTML内容
    :return: 提取的信息
    """
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们要提取所有的段落文本
    paragraphs = soup.find_all('p')
    return [p.get_text() for p in paragraphs]
 
def main():
    url = 'http://example.com'  # 替换为你要爬取的网页URL
    html = get_html(url)
    if html:
        parsed_info = parse_html(html)
        for info in parsed_info:
            print(info)
    else:
        print('Failed to retrieve HTML content')
 
if __name__ == '__main__':
    main()

这个简单的Python爬虫示例展示了如何使用requests库获取网页内容,以及如何使用BeautifulSoup库解析HTML并提取所需信息。这个例子只提取了段落文本,实际应用中可以根据需要提取其他信息,如链接、图片、标题等。

2024-08-25



import scrapy
 
class MySpider(scrapy.Spider):
    name = 'myspider'
    allowed_domains = ['example.com']
    start_urls = ['http://example.com/pages.html']
 
    def parse(self, response):
        # 提取页面中的所有链接并进一步跟踪
        for href in response.css('a::attr(href)').getall():
            # 构造绝对URL,并交给Scrapy进行爬取
            yield response.follow(href, self.parse)
 
        # 提取页面中的特定数据项
        for item in response.css('div.item'):
            # 提取链接、图片和标题
            url = item.css('a::attr(href)').extract_first()
            image = item.css('img::attr(src)').extract_first()
            title = item.css('a::text').extract_first()
 
            # 打印结果或者创建一个字典/对象来存储数据
            print(f"URL: {url}, Image: {image}, Title: {title}")

这个简单的爬虫示例展示了如何使用Scrapy框架的基本结构来爬取网页中的链接和数据。它定义了爬虫的名字、允许爬取的域名、起始URL和解析函数。解析函数会提取页面中所有的链接,并递归地跟踪它们,同时提取每个页面上指定的数据项。这个例子教会了如何使用Scrapy的CSS选择器来定位和提取数据,这是一种更直观和灵活的数据提取方法。

2024-08-25

在我们讨论如何通过Python爬虫作为副业的时候,我们需要考虑一些重要的法律和道德问题。这里我将提供一些可能的方法,但是请注意,您应该确保您的爬虫行为是道德和法律的。

  1. 数据分析服务:提供使用Python进行数据分析的服务。这可能包括清理和分析数据集、创建报告或进行机器学习项目。
  2. 网站开发:创建一个网站,提供数据抓取服务。这可能涉及到使用Flask或Django框架,并使用Python进行后端开发。
  3. 开发Chrome扩展程序:如果您是在浏览器中抓取数据,可以将这些功能集成到Chrome扩展程序中。
  4. 开发自动化测试工具:对于那些需要大量数据来测试其产品的公司,您可以开发自动化工具来帮助他们获取数据。
  5. 开发自动化脚本:为在线商店或其他平台自动化产品比价和购物。
  6. 开发API服务:提供API接口,让其他开发者可以使用您的爬虫数据。
  7. 数据集销售:将您爬取的数据集出售给需要的机构或个人。
  8. 提供在线课程或研讨会:教授如何进行网络爬虫开发。
  9. 开发付费QQ群:在QQ群中教授爬虫技术。
  10. 接私活:通过各种平台接单,比如码市、一品威客等。

在开始之前,请确保您已经了解并遵守与您打算抓取数据相关的服务条款和法律法规。不要进行违反版权或隐私的行为。如果您不确定,最好咨询法律专业人士。

以下是一个简单的Python爬虫示例,用于抓取一个网站的图片,并保存到本地:




import requests
from bs4 import BeautifulSoup
import os
 
url = 'http://example.com/images'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
 
# 创建一个文件夹用于保存图片
if not os.path.exists('images'):
    os.makedirs('images')
 
# 找到所有的img标签
for img in soup.find_all('img'):
    # 获取图片的链接
    img_url = img['src']
    response = requests.get(img_url)
    with open(os.path.join('images', os.path.basename(img_url)), 'wb') as f:
        f.write(response.content)

请注意,这只是一个简单的示例,您需要根据实际情况进行适当的修改。在开始任何爬虫项目之前,请始终确保您遵守您所抓取网站的robots.txt文件中的规定,并且了解您的行为可能带来的法律后果。如果您打算用爬虫来获取一些实际的经济利益,那么您应该在合法的范围内进行,并确保您的行为不会对您所抓取内容的网站造成损害。

2024-08-25



import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests.exceptions import ConnectionError, Timeout
 
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504], session=None):
    session = session or requests.Session()
    retries = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
    session.mount('http://', HTTPAdapter(max_retries=retries))
    session.mount('https://', HTTPAdapter(max_retries=retries))
    return session
 
# 使用示例
session = requests_retry_session()
 
try:
    response = session.get('http://example.com/api')
    # 处理响应
except ConnectionError as e:
    # 处理连接错误
    print(f"Connection error occurred: {e}")
except Timeout as e:
    # 处理请求超时
    print(f"Timeout error occurred: {e}")

这段代码定义了一个函数requests_retry_session,它创建了一个带有重试机制的requests.Session对象。当遇到网络问题(如连接失败、超时)时,会自动重试请求。可以通过调整参数来控制重试的次数、延迟因子以及状态码的白名单。

2024-08-25



import requests
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
 
# 定义一个函数来获取房源信息
def get_source_info(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    info_list = soup.select('.info-list li')
    info_dict = {}
    for info in info_list:
        key = info.select('span')[0].text
        value = info.select('a|span')[1].text if len(info.select('a|span')) > 1 else ''
        info_dict[key] = value
    return info_dict
 
# 定义一个函数来获取房源详细信息
def get_source_details(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    title = soup.select('.title-bar-01')[0].text
    info_list = soup.select('.house-parameter li')
    info_dict = {}
    for info in info_list:
        key = info.select('span')[0].text
        value = info.select('span')[1].text
        info_dict[key] = value
    return title, info_dict
 
# 定义一个函数来获取房源数据
def get_source_data(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data_list = soup.select('.house-list-wrap .house-list-item')
    source_data = []
    for data in data_list:
        info_dict = get_source_info(data.select('a')[0]['href'])
        info_dict['title'] = data.select('.house-title')[0].text
        info_dict['price'] = data.select('.price')[0].text
        source_data.append(info_dict)
    return source_data
 
# 获取二手房数据
source_data = get_source_data('http://ershou.jilin.cn/ershoufang/')
df = pd.DataFrame(source_data)
 
# 数据可视化
plt.figure(figsize=(20, 10))
plt.subplot(1, 2, 1)
plt.scatter(df['area'], df['price'])
plt.xlabel('Area (平方米)')
plt.ylabel('Price (万元)')
plt.title('二手房面积与价格关系散点图')
 
plt.subplot(1, 2, 2)
plt.hist(df['price'], bins=50)
plt.xlabel('Price (万元)')
plt.ylabel('Count')
plt.title('二手房价格分布直方图')
 
plt.show()

这段代码首先定义了一个函数get_source_info来解析房源列表页的每条房源信息,然后定义了一个函数get_source_details来解析房源详情页的标题和详细信息。最后,定义了一个函数get_source_data来获取整个房源页的数据,并将其存储为DataFrame格式,以便进行数据可视化分析。代码中使用了matplotlib.pyplot库来绘制散点图和直方图,展示了房源面积与价格之间的关系以及房源价格的分布情况。

2024-08-25



import pandas as pd
import jieba
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud
 
# 读取数据
df = pd.read_csv('data.csv', encoding='utf-8')
 
# 使用结巴分词
df['word_seg'] = df['comment'].apply(lambda x: ' '.join(jieba.cut(x)))
 
# 创建词频表
word_series = pd.Series(' '.join(df['word_seg']).split())
word_df = word_series.value_counts()[:1000].sort_values(ascending=False).reset_index()
word_df.columns = ['word', 'count']
 
# 词云可视化
cloud_mask = np.array(plt.imread('star.png'))
wordcloud = WordCloud(background_color='white', mask=cloud_mask, contour_width=3, contour_color='steelblue')
word_frequencies = {key: word_df.loc[i, 'count'] for i, key in enumerate(word_df['word'])}
wordcloud = wordcloud.fit_words(word_frequencies)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

这段代码首先导入了必要的Python库,并读取了数据。接着使用结巴分词库对评论进行了分词处理,并创建了一个词频表。最后,使用词频数据生成了一个词云图,展示了评论中最常见的词汇。这个过程展示了如何进行文本挖掘,分析情感,并以可视化的方式呈现结果。

2024-08-25



import requests
from bs4 import BeautifulSoup
 
def crawl_data(url):
    """
    从指定的url抓取数据
    """
    response = requests.get(url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        # 假设我们要抓取的数据在<div id="content"></div>内
        content = soup.find('div', {'id': 'content'})
        if content:
            return content.get_text()
    return "Failed to crawl data"
 
# 使用方法
url = "http://example.com"
print(crawl_data(url))

这段代码展示了如何使用Python的requests库和BeautifulSoup库来简单地抓取网页上的数据。函数crawl_data接收一个URL,向该URL发送HTTP GET请求,并使用BeautifulSoup解析返回的页面。然后它会尝试找到一个特定的HTML元素(这里是一个id为"content"的div标签),并返回该元素的文本内容。如果抓取失败,则返回一个错误消息。