2024-08-16



import requests
from bs4 import BeautifulSoup
 
def get_movie_details(movie_url):
    """
    获取电影详情
    :param movie_url: 电影URL
    :return: 电影详细信息字典
    """
    response = requests.get(movie_url)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'lxml')
        movie_details = {
            'name': soup.find('div', class_='hd').a.text.strip(),
            'rating': soup.find('div', class_='star').text.strip(),
            'quote': soup.find('div', class_='inq').text.strip(),
            'director': soup.find('div', class_='bd').find_all('p')[1].text.strip(),
        }
        return movie_details
    else:
        return "Error: Unable to fetch movie details."
 
# 示例使用
movie_url = 'https://movie.douban.com/subject/12927202/'
print(get_movie_details(movie_url))

这段代码定义了一个函数get_movie_details,它接受一个电影的URL作为参数,发送HTTP GET请求,并使用BeautifulSoup解析页面。然后,它提取电影的名称、评分、引言和导演信息,并以字典的形式返回。最后,我们提供了一个使用示例,展示了如何调用这个函数并打印结果。

2024-08-16



from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import Qt
 
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setCentralWidget(CustomWidget(self))
        self.show()
 
class CustomWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)
 
    def mousePressEvent(self, event):
        print("鼠标点击事件捕获:", event)
 
    def mouseMoveEvent(self, event):
        print("鼠标移动事件捕获:", event)
 
    def keyPressEvent(self, event):
        print("键盘按键事件捕获:", event)
 
def main():
    app = QApplication([])
    window = MainWindow()
    app.exec_()
 
if __name__ == '__main__':
    main()

这段代码演示了如何在PyQt5中创建一个窗口和一个自定义控件,并在这个控件中重写鼠标点击、移动和键盘按键事件处理函数,以便捕获并处理这些事件。当用户在控件上进行这些操作时,相关的事件信息会被打印到控制台。这对于理解事件传递和捕获的原理非常有帮助。

2024-08-16



// 导入必要的类
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.TreeSet;
import java.util.Set;
 
public class CollectionExample {
    public static void main(String[] args) {
        // 创建HashSet实例
        Set<String> hashSet = new HashSet<>();
        hashSet.add("HashSet1");
        hashSet.add("HashSet2");
        hashSet.add("HashSet3");
        System.out.println("HashSet: " + hashSet);
 
        // 创建LinkedHashSet实例
        Set<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("LinkedHashSet1");
        linkedHashSet.add("LinkedHashSet2");
        linkedHashSet.add("LinkedHashSet3");
        System.out.println("LinkedHashSet: " + linkedHashSet);
 
        // 创建TreeSet实例
        Set<String> treeSet = new TreeSet<>();
        treeSet.add("TreeSet1");
        treeSet.add("TreeSet2");
        treeSet.add("TreeSet3");
        System.out.println("TreeSet: " + treeSet);
    }
}

这段代码演示了如何创建和使用HashSetLinkedHashSetTreeSet三种类型的集合。每个集合都添加了一些字符串元素,并打印出集合的内容。这有助于理解这些集合的特性和用法。

2024-08-16



import pandas as pd
 
# 创建一个简单的DataFrame
data = {'Name': ['John', 'Anna', 'Peter', 'Linda'],
        'Age': [28, 23, 34, 29]}
df = pd.DataFrame(data)
 
# 打印DataFrame
print(df)
 
# 将DataFrame导出到CSV文件
df.to_csv('output.csv', index=False)
 
# 从CSV文件读取数据到新的DataFrame
df_from_csv = pd.read_csv('output.csv')
 
# 打印新的DataFrame
print(df_from_csv)

这段代码展示了如何使用pandas库创建一个简单的DataFrame,并将其导出为CSV文件,然后再从CSV文件读取数据到新的DataFrame。这个过程是数据处理和分析的常见步骤,pandas库提供了丰富的功能来处理和分析数据。

2024-08-16

以下是一个简单的Python爬虫示例,使用requests库获取网页内容,并使用BeautifulSoup解析网页。




import requests
from bs4 import BeautifulSoup
 
# 目标网页URL
url = 'https://example.com'
 
# 发送HTTP请求
response = requests.get(url)
 
# 检查请求是否成功
if response.status_code == 200:
    # 使用BeautifulSoup解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 提取需要的数据,例如所有段落文本
    paragraphs = soup.find_all('p')
    for p in paragraphs:
        print(p.get_text())
else:
    print(f"Error: {response.status_code}")
 

确保在运行此代码前安装所需的库:




pip install requests beautifulsoup4

这个简单的爬虫示例获取了指定URL的内容,并打印出所有段落标签<p>的文本内容。在实际应用中,你需要根据目标网站的结构和你想要抓取的数据来调整选择器和数据提取逻辑。

2024-08-16



import numpy as np
import sounddevice as sd
import matplotlib.pyplot as plt
 
# 音频信号生成函数
def generate_audio_signal(frequency, duration, amplitude=1.0, sample_rate=44100):
    t = np.linspace(0, duration, duration * sample_rate, False)
    signal = amplitude * np.sin(2 * np.pi * frequency * t)
    return signal
 
# 播放音频函数
def play_audio(signal, sample_rate):
    sd.play(signal, sample_rate)
    sd.wait()
 
# 可视化音频函数
def visualize_audio(signal, sample_rate):
    time = np.arange(len(signal)) / sample_rate
    plt.figure()
    plt.plot(time, signal)
    plt.xlabel('Time (s)')
    plt.ylabel('Amplitude')
    plt.title('Audio Waveform')
    plt.show()
 
# 示例使用
frequency = 440  # 音调频率(A4)
duration = 1  # 持续时间1秒
amplitude = 0.5  # 振幅
sample_rate = 44100  # 采样率
 
# 生成音频信号
audio_signal = generate_audio_signal(frequency, duration, amplitude, sample_rate)
 
# 播放音频
print("播放音频...")
play_audio(audio_signal, sample_rate)
 
# 可视化音频波形
visualize_audio(audio_signal, sample_rate)

这段代码首先导入了必要的Python库,然后定义了一个函数用于生成音频信号,另一个函数用于播放音频,还有一个函数用于将音频信号可视化。最后,代码示例展示了如何设置音调频率、持续时间和振幅,并生成、播放和可视化一个音频信号。

2024-08-14

Matplotlib 是 Python 中一个非常流行的可视化库。plt.rcParams 是一个字典,用于控制 Matplotlib 图表的默认样式参数。通过修改这个字典的内容,我们可以改变包括图表的大小、线条样式、坐标轴、颜色等在内的各种属性。

原理

plt.rcParams 是一个全局的字典,包含了控制 Matplotlib 行为的参数。这些参数可以在 Matplotlib 初始化时设置,并且会影响到所有后续创建的图形。

作用

使用 plt.rcParams 可以方便地设置图表的各种默认参数,例如:

  • 图表的尺寸
  • 线条的宽度和样式
  • 坐标轴的显示
  • 图例的位置
  • 文本的字体和大小
  • 图表的背景色

注意事项

在修改 plt.rcParams 时,应该谨慎处理,因为这将影响到你之后所有图表的默认样式。如果只想改变某一个图表的样式,应该使用 plt.plot 等函数的参数来进行局部修改。

示例代码




import matplotlib.pyplot as plt
 
# 设置默认的线宽为2
plt.rcParams['lines.linewidth'] = 2
 
# 设置默认的图表背景色为白色
plt.rcParams['figure.facecolor'] = 'white'
 
# 绘制一个简单的图表
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

在这个例子中,我们设置了默认的线宽和图表背景色,并绘制了一个简单的折线图。这些设置会应用到所有图表,除非在绘制图表时使用 plt.plot 等函数的参数进行局部覆盖。

2024-08-14



import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
 
# 生成模拟数据
np.random.seed(0)
n_samples = 100
X = np.random.rand(n_samples, 2)  # 2个特征
y = 0.5 * X[:, 0] ** 2 + 0.3 * X[:, 1] ** 2 + 0.2 * np.random.randn(n_samples)  # 目标值,含噪声
 
# 拟合多元线性回归模型
model = LinearRegression()
model.fit(X, y)
 
# 绘制3D散点图
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X[:, 1], y, c='r', marker='o')
 
# 绘制回归平面
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))
z = model.predict(np.c_[xx.ravel(), yy.ravel()])
z = z.reshape(xx.shape)
ax.plot_surface(xx, yy, z, alpha=0.5)
 
# 设置标签
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
 
# 展示图形
plt.show()

这段代码首先生成了一个包含噪声的多元回归问题,然后使用sklearn.linear_model.LinearRegression进行拟合,并绘制了数据点的3D散点图以及回归平面。这是一个很好的教学示例,展示了如何处理多元回归问题并可视化结果。

2024-08-14

创建conda环境:




conda create --name myenv python=3.8

激活环境:




conda activate myenv

配置镜像源(以清华大学镜像为例):




conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes

常用命令:

  • 列出所有环境:conda env list
  • 删除环境:conda env remove --name myenv
  • 更新环境中的包:conda update --all
  • 搜索包:conda search numpy
  • 安装包:conda install numpy
  • 移除包:conda remove numpy

安装Jupyter:




conda install jupyter notebook

启动Jupyter Notebook:




jupyter notebook

配置PyCharm中的conda环境:

  1. 打开PyCharm,点击 File > Settings (或 PyCharm > Preferences 在Mac上)。
  2. 导航到 Project: YourProjectName > Python Interpreter
  3. 点击右上角的齿轮图标,然后选择 Add...
  4. 在弹出窗口中,选择 Conda Environment
  5. Interpreter 一栏中,点击文件夹图标,选择conda环境的路径。
  6. 如果需要,配置 Conda Excutable 路径。
  7. 点击 OK 应用更改。

以上步骤会在PyCharm中配置conda环境,使你可以在其中创建、管理项目,并使用conda来安装和更新包。

2024-08-14



class Singleton:
    _instance = None
 
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance
 
class MySingleton(Singleton):
    def __init__(self, name):
        self.name = name
 
# 使用单例
a = MySingleton('Singleton A')
b = MySingleton('Singleton B')
 
# a和b将引用同一个对象,因为MySingleton是Singleton的子类,而_instance是在Singleton中定义的
print(a is b)  # 输出: True

这个代码实例展示了如何在Python中实现单例模式。通过继承一个单例基类,我们可以轻松地在程序中创建单例类。这种方法使得单例类可以在需要的时候共享实例,从而节省内存。