调整百度新闻,加入#号

This commit is contained in:
liuwei
2025-02-14 08:58:48 +08:00
parent 4d1811ce23
commit e50ef0ce06
5 changed files with 173 additions and 56 deletions

View File

@@ -104,7 +104,7 @@ class News(object):
title = article['word']
# url = article['url']
# 使用f-string格式化字符串并添加到output中
output += f"{index}. : {title}\n"
output += f"{index} :#{title}\n"
# 输出最终的字符串(这里只是为了展示,实际上你可以根据需要处理这个字符串)
return output

20
task/dateparser_test.py Normal file
View File

@@ -0,0 +1,20 @@
import parsedatetime as pdt
from datetime import datetime
# 初始化 Calendar 对象
cal = pdt.Calendar()
def parse_natural_language_time(text):
time_struct, parse_status = cal.parse(text)
if parse_status == 1:
# 将解析后的时间结构转换为 datetime 对象
parsed_time = datetime(*time_struct[:6])
print(f"Parsed time: {parsed_time}")
return parsed_time
else:
print(f"Could not parse time for: {text}")
return None
# 示例输入
test_input = "明天上午9点开会"
parsed_time = parse_natural_language_time(test_input)

View File

@@ -1,68 +1,157 @@
import sqlite3
import datetime
import pymysql
import dateparser
import schedule
import time
# SQLite数据库文件名
DB_FILE = 'tasks.db'
# 配置数据库连接
db_config = {
'host': '192.168.2.32', # 替换为你的MariaDB服务器地址
'user': 'root', # 替换为你的MariaDB用户名
'password': 'lw123456', # 替换为你的MariaDB密码
'database': 'message_archive'
}
# 初始化数据库
def init_db():
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS tasks
(id INTEGER PRIMARY KEY AUTOINCREMENT,
description TEXT NOT NULL,
reminder_time TEXT NOT NULL)''')
conn.commit()
conn.close()
# 数据库连接
def get_db_connection():
connection = pymysql.connect(**db_config)
return connection
# 添加任务
def add_task(description, time_str):
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
time_obj = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
c.execute("INSERT INTO tasks (des cription, reminder_time) VALUES (?, ?)",
(description, time_obj.isoformat()))
conn.commit()
conn.close()
print(f"Task '{description}' added for {time_str}")
# 解析自然语言时间
def parse_natural_language_time(text):
parsed_time = dateparser.parse(text)
return parsed_time
# 检查并执行任务
def check_tasks():
now = datetime.datetime.now().isoformat()
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute("SELECT * FROM tasks WHERE reminder_time <= ?", (now,))
tasks = c.fetchall()
# 插入任务到数据库
def insert_task_to_db(description, reminder_time, task_type):
connection = get_db_connection()
cursor = connection.cursor()
# 插入任务信息
query = "INSERT INTO tasks (task_description, reminder_time, task_type) VALUES (%s, %s, %s)"
cursor.execute(query, (description, reminder_time, task_type))
connection.commit()
cursor.close()
connection.close()
# 提醒任务(根据任务描述输出具体内容)
def reminder_task(task_id):
connection = get_db_connection()
cursor = connection.cursor()
# 获取任务描述
query = "SELECT task_description FROM tasks WHERE task_id = %s"
cursor.execute(query, (task_id,))
task = cursor.fetchone()
if task:
task_description = task[0]
print(f"Reminder: {task_description}") # 输出具体的任务内容
cursor.close()
connection.close()
# 调度单次任务
def schedule_single_task(reminder_time, task_id):
schedule.every().day.at(reminder_time).do(reminder_task, task_id=task_id)
print(f"Single task scheduled at {reminder_time}.")
# 调度周期性任务(例如:每天执行)
def schedule_recurring_task(reminder_time, task_id):
schedule.every().day.at(reminder_time).do(reminder_task, task_id=task_id)
print(f"Recurring task scheduled every day at {reminder_time}.")
# 处理用户输入
def handle_user_input(user_input, task_type):
parsed_time = parse_natural_language_time(user_input)
print(parsed_time)
if parsed_time:
formatted_time = parsed_time.strftime('%H:%M')
print(f"Scheduling task for {formatted_time}")
# 将任务存入数据库
insert_task_to_db(user_input, formatted_time, task_type)
# 获取插入的任务ID
connection = get_db_connection()
cursor = connection.cursor()
cursor.execute("SELECT LAST_INSERT_ID()")
task_id = cursor.fetchone()[0]
cursor.close()
connection.commit()
connection.close()
# 根据任务类型调度任务
if task_type == 'single':
schedule_single_task(formatted_time, task_id)
elif task_type == 'recurring':
schedule_recurring_task(formatted_time, task_id)
# 查询指定类型的任务
def get_tasks_by_type(task_type):
connection = get_db_connection()
cursor = connection.cursor()
# 查询指定类型的任务
query = "SELECT task_id, task_description, reminder_time, status, task_type FROM tasks WHERE task_type = %s"
cursor.execute(query, (task_type,))
tasks = cursor.fetchall()
for task in tasks:
print(f"Executing task: {task[1]}")
# 如果只想执行一次,则删除任务
c.execute("DELETE FROM tasks WHERE id = ?", (task[0],))
conn.commit()
conn.close()
print(
f"Task ID: {task[0]}, Description: {task[1]}, Reminder Time: {task[2]}, Status: {task[3]}, Type: {task[4]}")
cursor.close()
connection.close()
# 定时检查任务
schedule.every(1).minute.do(check_tasks) # 每分钟检查一次任务
# 更新任务状态
def update_task_status(task_id, status):
connection = get_db_connection()
cursor = connection.cursor()
# 更新任务状态
query = "UPDATE tasks SET status = %s WHERE task_id = %s"
cursor.execute(query, (status, task_id))
connection.commit()
cursor.close()
connection.close()
# 获取所有周期性任务
def get_all_recurring_tasks():
get_tasks_by_type('recurring')
# 获取所有单次任务
def get_all_single_tasks():
get_tasks_by_type('single')
# 主函数(示例输入)
def main():
# 示例:单次任务
user_input_single = "提醒我明天上午9点开会"
handle_user_input(user_input_single, 'single')
# 示例:周期性任务
user_input_recurring = "每天上午9点提醒我开会"
handle_user_input(user_input_recurring, 'recurring')
# # 启动定时任务调度
# while True:
# schedule.run_pending()
# time.sleep(1)
# 示例使用
if __name__ == "__main__":
init_db() # 初始化数据库(如果尚未初始化)
# 添加示例任务(注意:时间应该设置为未来的时间以测试)
add_task("Buy groceries", "2024-12-20 14:02:50") # 修改为未来时间进行测试
add_task("Attend meeting", "2024-12-20 14:03:50") # 修改为未来时间进行测试
# 由于我们设置了未来的时间,因此需要使用一个足够长的时间循环来等待任务执行
# 在实际应用中,你可能会有一个更优雅的方式来停止循环(例如监听特定事件)
print("Starting task scheduler...")
try:
while True:
schedule.run_pending()
time.sleep(1) # 等待下一分钟
except KeyboardInterrupt:
print("Scheduler stopped manually.")
# main()
parsed_time = dateparser.parse('每天上午9:00提醒我开会', settings={'TIMEZONE': 'Asia/Shanghai'},)
print(parsed_time)

Binary file not shown.

8
task/tasks.sql Normal file
View File

@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS tasks (
task_id INT AUTO_INCREMENT PRIMARY KEY, -- 任务ID自增
task_description VARCHAR(255) NOT NULL, -- 任务描述
reminder_time TIME NOT NULL, -- 提醒时间
task_type ENUM('single', 'recurring') DEFAULT 'single', -- 任务类型:单次或周期性
status ENUM('pending', 'completed') DEFAULT 'pending', -- 任务状态:待办或已完成
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- 创建时间,默认为当前时间
);