boxmoe_header_banner_img

Hello! 欢迎来到豌豆高清!

文章导读

Flask开发双色球智能分析工具


avatar
admin 2025 年 8 月 3 日 57


初衷:
1. 成年人给心灵找的一种寄托罢了。
2.最近几年一直在python的各种洗脑下,学习着python。
3.最终抵不住诱惑,学着写起来了。
该工具仅作学习flask交流,切勿用于非法用途,生成数据仅供娱乐,切勿轻信!
简单讲解功能思路:
使用流程:
支持手动输入号码,
文件上传方式支持.txt文件

点击”解析文件”按钮解析号码

解析成功后自动填充到输入框中

添加验证机制:

只接受.txt文本文件

自动验证号码有效性(范围、重复等)

最多导入10组有效号码

错误处理:

文件格式错误提示

号码验证失败提示

上传失败提示

注意:需要自行创建虚拟环境venv,后安装:
Package Version
—————— ——–
blinker 1.9.0
certifi 2025.8.3
charset-normalizer 3.4.2
click 8.2.1
colorama 0.4.6
Flask 3.1.1
idna 3.10
itsdangerous 2.2.0
Jinja2 3.1.6
MarkupSafe 3.0.2
pip 25.2
requests 2.32.4
setuptools 57.4.0
urllib3 2.5.0
Werkzeug 3.1.3


from flask import Flask, render_template, request, jsonify
from collections import Counter
import random
from datetime import datetime, timedelta
from typing import List, Tuple, Dict, Union
import os
import re

app = Flask(__name__)
app.config[‘UPLOAD_FOLDER’] = ‘uploads’
os.makedirs(app.config[‘UPLOAD_FOLDER’], exist_ok=True)

# 类型别名
LotteryNumber = Tuple[List[int], int]
ValidationResult = Tuple[bool, str]
ComparisonResult = Dict[str, Union[str, int, bool]]

class LotteryUtils:
“””工具类”””

@staticmethod
def is_draw_day(date: datetime.date) -> bool:
“””判断是否为开奖日(周二、四、日)”””
return date.weekday() in [1, 3, 6] # 周二=1, 周四=3, 周日=6

@staticmethod
def get_next_draw_date(current_date: datetime.date) -> str:
“””计算下一个开奖日期”””
weekday = current_date.weekday()
if weekday in [0, 3, 6]: # 周一、周四、周日
days = 2 if weekday == 0 else (3 if weekday == 3 else 2)
else:
days = (1 – weekday) % 7 if weekday < 1 else \ (3 - weekday) % 7 if weekday < 3 else \ (6 - weekday) % 7 return (current_date + timedelta(days=days)).strftime("%Y年%m月%d日") class LotteryValidator: """号码验证""" @staticmethod def validate_red(reds: List[int]) -> ValidationResult:
if len(set(reds)) != 6:
return False, “红球号码不能重复”
if any(num < 1 or num > 33 for num in reds):
return False, “红球号码必须在1-33范围内”
return True, “”

@staticmethod
def validate_blue(blue: int) -> ValidationResult:
if blue < 1 or blue > 16:
return False, “蓝球号码必须在1-16范围内”
return True, “”

@classmethod
def validate_numbers(cls, reds: List[int], blue: int) -> ValidationResult:
valid, msg = cls.validate_red(reds)
return (valid, msg) if not valid else cls.validate_blue(blue)

class LotteryAnalyzer:
“””号码分析”””

@staticmethod
def analyze_frequency(numbers: List[LotteryNumber]) -> Tuple[List[int], List[int]]:
red_counter = Counter()
blue_counter = Counter()
for reds, blue in numbers:
red_counter.update(reds)
blue_counter.update([blue])
return (
[num for num, _ in red_counter.most_common()],
[num for num, _ in blue_counter.most_common()]
)

class LotteryGenerator:
“””号码生成”””

@staticmethod
def generate(common_reds: List[int], common_blues: List[int]) -> LotteryNumber:
num_common = random.randint(4, 5)
selected = common_reds[:num_common]
remaining = [n for n in range(1, 34) if n not in selected]
selected.extend(random.sample(remaining, 6 – num_common))
blue = (random.choice(common_blues[:3])
if random.random() < 0.7 and common_blues else random.randint(1, 16)) return sorted(selected), blue class LotteryComparator: """结果比较""" PRIZE_RULES = [ {"condition": lambda r, b: r == 6 and b, "prize": "一等奖"}, {"condition": lambda r, b: r == 6, "prize": "二等奖"}, {"condition": lambda r, b: r == 5 and b, "prize": "三等奖"}, {"condition": lambda r, b: r == 5 or (r == 4 and b), "prize": "四等奖"}, {"condition": lambda r, b: r == 4 or (r == 3 and b), "prize": "五等奖"}, {"condition": lambda r, b: b, "prize": "六等奖"}, ] @classmethod def compare(cls, numbers: List[LotteryNumber], last_reds: List[int], last_blue: int) -> List[ComparisonResult]:
return [{
‘numbers’: f”{‘ ‘.join(f'{n:02d}’ for n in reds)} + {blue:02d}”,
‘matched_reds’: len(set(reds) & set(last_reds)),
‘matched_blue’: blue == last_blue,
‘prize’: next((r[“prize”] for r in cls.PRIZE_RULES if r[“condition”](len(set(reds) & set(last_reds)), blue == last_blue)), “未中奖”)
} for reds, blue in numbers]

class LotteryDataFetcher:
@staticmethod
def get_latest_draw():
“””获取最新开奖数据(现在由用户手动输入)”””
# 默认模拟数据
return [2, 6, 14, 15, 24, 26], 8, datetime.now().strftime(‘%Y年%m月%d日’)

@app.route(‘/’)
def index():
return render_template(‘index.html’)

@app.route(‘/upload’, methods=[‘POST’])
def upload_file():
if ‘file’ not in request.files:
return jsonify({‘error’: ‘未上传文件’}), 400

file = request.files[‘file’]
if not file or file.filename == ”:
return jsonify({‘error’: ‘未选择文件’}), 400

if not file.filename.lower().endswith(‘.txt’):
return jsonify({‘error’: ‘仅支持.txt文件’}), 400

try:
content = file.stream.read().decode(‘utf-8′)
numbers = []
for line in content.splitlines():
nums = re.findall(r’\d+’, line)
if len(nums) >= 7:
try:
reds = [int(n) for n in nums[:6]]
blue = int(nums[6])
valid, _ = LotteryValidator.validate_numbers(reds, blue)
if valid:
numbers.append((sorted(reds), blue))
except ValueError:
continue

if not numbers:
return jsonify({‘error’: ‘未找到有效号码’}), 400

return jsonify({
‘success’: True,
‘count’: len(numbers),
‘numbers’: numbers[:10]
})
except Exception as e:
return jsonify({‘error’: f’处理失败: {str(e)}’}), 500

@app.route(‘/set_last_draw’, methods=[‘POST’])
def set_last_draw():
“””设置上期开奖号码”””
try:
data = request.json
reds = [int(n) for n in data[‘reds’]]
blue = int(data[‘blue’])
draw_date = data.get(‘draw_date’, datetime.now().strftime(‘%Y年%m月%d日’))

valid, msg = LotteryValidator.validate_numbers(reds, blue)
if not valid:
return jsonify({‘error’: msg}), 400

# 更新最新开奖数据
LotteryDataFetcher.last_reds = reds
LotteryDataFetcher.last_blue = blue
LotteryDataFetcher.last_draw_date = draw_date

return jsonify({
‘success’: True,
‘message’: ‘上期开奖号码设置成功’
})
except Exception as e:
return jsonify({‘error’: f’设置失败: {str(e)}’}), 500

@app.route(‘/generate’, methods=[‘POST’])
def generate():
try:
# 处理用户输入
user_numbers = []
for i in range(1, 11):
reds = [int(request.form.get(f’red_{i}_{j}’)) for j in range(1, 7)]
blue = int(request.form.get(f’blue_{i}’))
valid, msg = LotteryValidator.validate_numbers(reds, blue)
if not valid:
return jsonify({‘error’: f’第{i}组: {msg}’}), 400
user_numbers.append((reds, blue))

# 获取开奖数据(现在使用用户设置的数据)
if hasattr(LotteryDataFetcher, ‘last_reds’):
last_reds = LotteryDataFetcher.last_reds
last_blue = LotteryDataFetcher.last_blue
draw_date = LotteryDataFetcher.last_draw_date
else:
last_reds, last_blue, draw_date = LotteryDataFetcher.get_latest_draw()

# 分析生成
common_reds, common_blues = LotteryAnalyzer.analyze_frequency(user_numbers)
new_numbers = [LotteryGenerator.generate(common_reds, common_blues) for _ in range(5)]
results = LotteryComparator.compare(new_numbers, last_reds, last_blue)

return jsonify({
‘draw_date’: draw_date,
‘last_draw’: f”{‘ ‘.join(f'{n:02d}’ for n in last_reds)} + {last_blue:02d}”,
‘common_reds’: ‘ ‘.join(f'{n:02d}’ for n in common_reds[:10]),
‘common_blues’: ‘ ‘.join(f'{n:02d}’ for n in common_blues[:3]),
‘results’: results
})
except Exception as e:
return jsonify({‘error’: f’服务器错误: {str(e)}’}), 500

if __name__ == ‘__main__’:
app.run(debug=True)

资源下载
免费资源
链接点击下载提取码: 7rxd复制
资源均来自网络,若有侵权,请联系删除,为您带来不便,敬请谅解!


评论(0)

查看评论列表

暂无评论


发表评论