判断连号范围查询例子

表Tb有两个长整型字段F1,F2

F1 F2
---------------------------
100 109
110 119
120 129
140 149
150 159
160 169


问题:
100 至 129 是连续的,140 至 169是连续的,如何得到

F1 F2
---------------------------
100 129
140 169

--> 生成测试数据表:tb

If not object_id('[tb]') is null
Drop table [tb]
Go
Create table [tb]([F1] int,[F2] int)
Insert [tb]
Select 100,109 union all
Select 110,119 union all
Select 120,129 union all
Select 140,149 union all
Select 150,159 union all
Select 160,169
Go
--Select * from [tb]

-->SQL2005查询如下:
select a.F1,b.F2
from
(
select rn=row_number()over(order by F1),F1 from tb t
where not exists(select 1 from tb where abs(F2-t.F1)=1)
) a
join
(
select rn=row_number()over(order by F2),F2 from tb t
where not exists(select 1 from tb where abs(t.F2-F1)=1)
) b
on a.rn=b.rn
/*
F1 F2
----------- -----------
100 129
140 169

(2 行受影响)
*/

-->SQL2000查询如下:
select a.F1,min(b.F2) F2
from
(
select F1 from tb t
where not exists(select 1 from tb where abs(F2-t.F1)=1)
) a
join
(
select F2 from tb t
where not exists(select 1 from tb where abs(t.F2-F1)=1)
) b
on a.F1<=b.F2
group by a.F1
/*
F1 F2
----------- -----------
100 129
140 169

(2 行受影响)
*/
http://topic.youkuaiyun.com/u/20090903/21/2aa383d6-ee3f-4236-9f4b-994d8deb7699.html?77772

仔细阅读下面【Python】代码,判断是否会运行报错? 如果会报错,请说明原因,并输出解决方法; 如果不会报错,请回答“无错误” 你需要处理的代码为:【分析代码不能运行的原因,按照运行的线程,模块2运行结束后,就运行模块3,可模块3 一直没有反应(具体指事件C号码池的控制台没有提供传输数据成功或接收数据成功,它能够反应模块3是否运行)# 全局配置 VERSION = "大乐透分析工具 v3.0" event_c = None # 全局事件C对象 file_lock = threading.Lock() # 文件读取锁 data_queue = queue.Queue() # 数据队列 def install_required_packages(): """安装必要的Python包""" required_packages = { 'pandas': 'pandas', 'numpy': 'numpy', 'scipy': 'scipy', 'chardet': 'chardet' } for package_name, install_name in required_packages.items(): try: __import__(package_name) except ImportError: print(f"正在安装 {package_name}…") subprocess.check_call([sys.executable, "-m", "pip", "install", install_name]) def detect_encoding(file_path): """检测文件编码""" try: with open(file_path, 'rb') as f: rawdata = f.read(100000) result = chardet.detect(rawdata) print(f"编码检测结果: {result['encoding']} (置信度: {result['confidence']:.1%})") return result['encoding'] or 'gb2312' except Exception as e: print(f"编码检测失败: {str(e)}") return 'gb2312' def preprocess_data(df): """数据预处理""" # 列名标准化 df = df.rename(columns={ '开奖期号': '期号', '前1': '前1', '前2': '前2', '前3': '前3', '前4': '前4', '前5': '前5', '后1': '后1', '后2': '后2' }) # 校验必要列 required_cols = {'期号', '前1', '前2', '前3', '前4', '前5', '后1', '后2'} missing = required_cols - set(df.columns) if missing: actual_cols = "\n".join(df.columns) raise ValueError(f"列名不匹配!\n需要列: {required_cols}\n实际列:\n{actual_cols}") # 转换号码为整数 def convert_number(col, min_val, max_val): df[col] = pd.to_numeric(df[col], errors='coerce').fillna(random.randint(min_val, max_val)).astype(int) df[col] = df[col].apply(lambda x: x if min_val <= x <= max_val else random.randint(min_val, max_val)) return df[col] # 处理前区号码 for col in ['前1', '前2', '前3', '前4', '前5']: convert_number(col, 1, 35) # 处理后区号码 for col in ['后1', '后2']: convert_number(col, 1, 12) # 合并号码列 df['前区号码'] = df[['前1', '前2', '前3', '前4', '前5']].values.tolist() df['后区号码'] = df[['后1', '后2']].values.tolist() return df def start_threads(): """启动所有分析线程""" file_path = r'F:\超级\历史数据\历史数据.csv' encoding = detect_encoding(file_path) df = pd.read_csv(file_path, encoding=encoding) df = preprocess_data(df) # 启动分析线程 threads = [ threading.Thread(target=module2_analysis, args=("模块2:组合分析", df)), threading.Thread(target=module3_analysis, args=("模块3:跟随分析", df)), threading.Thread(target=module4_analysis, args=("模块4:趋势分析", df)), threading.Thread(target=module5_analysis, args=("模块5:数字生成模型", df)) ] for thread in threads: thread.start() for thread in threads: thread.join() # 收集所有线程的结果 results = {} while not data_queue.empty(): name, data = data_queue.get() if data is not None: results[name] = data return results # ======== 模块2:组合分析 ========== def module2_analysis(name, df): """组合分析模块""" try: analyzer = CombinationAnalyzer(df) result = analyzer.analyze() data_queue.put((name, result)) print(f"{name} 分析完成") except Exception as e: print(f"{name} 分析失败: {str(e)}") class CombinationAnalyzer: def __init__(self, df): self.df = df def analyze(self): # 实现组合分析逻辑 return {"combinations": "组合分析结果"} # ======= 模块3:跟随分析 ====== def module3_analysis(name, df): """跟随分析模块""" try: analyzer = FollowingAnalyzer(df) result = analyzer.analyze() data_queue.put((name, result)) print(f"{name} 分析完成") except Exception as e: print(f"{name} 分析失败: {str(e)}") class FollowingAnalyzer: def __init__(self, df): self.df = df def analyze(self): # 实现跟随分析逻辑 return {"following": "跟随分析结果"} # ======= 模块4:趋势分析 ======= def module4_analysis(name, df): """趋势分析模块""" try: analyzer = TrendAnalyzer(df) result = analyzer.analyze() data_queue.put((name, result)) print(f"{name} 分析完成") except Exception as e: print(f"{name} 分析失败: {str(e)}") class TrendAnalyzer: def __init__(self, df): self.df = df def analyze(self): return { "sum": self.sum_analysis(), "prime": self.prime_composite_analysis(), "odd_even": self.odd_even_analysis(), "zone": self.zone_analysis(), "consecutive": self.consecutive_analysis(), "hot_cold": self.hot_cold_analysis(), "back_zone": self.back_zone_analysis() } def sum_analysis(self): """和值分析""" df = self.df.copy() df['和值'] = df['前区号码'].apply(sum) return df['和值'].describe().to_dict() def prime_composite_analysis(self): """质合比分析""" primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} df = self.df.copy() df['质数个数'] = df['前区号码'].apply(lambda nums: sum(1 for n in nums if n in primes)) return df['质数个数'].value_counts().to_dict() def odd_even_analysis(self): """奇偶比分析""" df = self.df.copy() df['奇数个数'] = df['前区号码'].apply(lambda nums: sum(1 for n in nums if n % 2 == 1)) return df['奇数个数'].value_counts().to_dict() def zone_analysis(self): """区间分析""" zones = [ (1, 5), (6, 10), (11, 15), (16, 20), (21, 25), (26, 30), (31, 35) ] zone_counts = defaultdict(int) for nums in self.df['前区号码']: for num in nums: for i, (low, high) in enumerate(zones): if low <= num <= high: zone_counts[f"区{i+1}"] += 1 return dict(zone_counts) def consecutive_analysis(self): """连号分析""" consecutive_counts = Counter() for nums in self.df['前区号码']: sorted_nums = sorted(nums) for i in range(len(sorted_nums)-1): if sorted_nums[i+1] - sorted_nums[i] == 1: consecutive_counts[f"{sorted_nums[i]}-{sorted_nums[i+1]}"] += 1 return dict(consecutive_counts) def hot_cold_analysis(self): """冷热号分析""" all_numbers = [] for nums in self.df['前区号码']: all_numbers.extend(nums) counter = Counter(all_numbers) return { "hot": [num for num, _ in counter.most_common(5)], "cold": [num for num, _ in counter.most_common()[:-6:-1]] } def back_zone_analysis(self): """后区分析""" back_numbers = [] for nums in self.df['后区号码']: back_numbers.extend(nums) counter = Counter(back_numbers) return { "hot": [num for num, _ in counter.most_common(3)], "cold": [num for num, _ in counter.most_common()[:-4:-1]] } # ===== 模块5:数字生成模型 ====== def module5_analysis(name, df): """数字生成模块""" try: analyzer = NumberGenerator(df) result = analyzer.generate() data_queue.put((name, result)) print(f"{name} 分析完成") except Exception as e: print(f"{name} 分析失败: {str(e)}") class NumberGenerator: def __init__(self, df): self.df = df def generate(self): # 实现数字生成逻辑 return {"numbers": "生成号码结果"} if __name__ == "__main__": install_required_packages() results = start_threads() print("所有分析结果:", results) # =================== 模块1 手动输入 =============================== import json import threading from typing import List import tkinter as tk from tkinter import messagebox import time import queue # Kafka 相关库的导入 from confluent_kafka import Producer, Consumer # 创建专用通道 channel_a = queue.Queue() class EventPublisher: """事件发布器基类""" def publish_event(self, event_data: dict, channel: queue.Queue): """发布事件到指定通道""" try: channel.put(event_data) return True except Exception as e: print(f"[模块1] 传输数据失败: {str(e)}") return False class EventSubscriber: """事件订阅器基类""" def __init__(self, channel: queue.Queue): self._running = False self._thread = None self._channel = channel def start(self): """启动订阅线程""" self._running = True self._thread = threading.Thread(target=self._event_loop) self._thread.daemon = True self._thread.start() def stop(self): """停止订阅线程""" self._running = False if self._thread: self._thread.join() def _event_loop(self): """事件循环""" while self._running: try: event = self._channel.get(timeout=1) if event: self.handle_event(event) except queue.Empty: continue def handle_event(self, event: dict): """处理事件(子类实现)""" raise NotImplementedError class Module1(EventPublisher): def __init__(self): super().__init__() self._fronts = [] self._backs = [] self._lock = threading.Lock() def _validate_numbers(self, fronts: List[int], backs: List[int]) -> bool: """验证号码有效性(内部方法)""" if not all(1 <= num <= 35 for num in fronts): return False if not all(1 <= num <= 12 for num in backs): return False return True def _deduplicate_numbers(self, numbers: List[int]) -> List[int]: """去重并排序(内部方法)""" return sorted(list(set(numbers))) def manual_input(self, fronts: List[int], backs: List[int]): """ 手动输入号码并发布事件 """ if not self._validate_numbers(fronts, backs): print("[模块1] 数据无效,发送失败!") return False clean_fronts = self._deduplicate_numbers(fronts) clean_backs = self._deduplicate_numbers(backs) event = { "event_type": "numbers_updated", "source": "module1", "data": { "fronts": clean_fronts, "backs": clean_backs }, "timestamp": int(time.time()) } success = self.publish_event(event, channel_a) if success: with self._lock: self._fronts = clean_fronts self._backs = clean_backs return True else: return False def set_module_data(self, fronts: List[int], backs: List[int]): """设置模块数据""" return self.manual_input(fronts, backs) def get_module_data(self) -> dict: """获取模块数据""" with self._lock: return {"front": self._fronts.copy(), "back": self._backs.copy()} class EventCPool(EventSubscriber): """事件C号码池订阅者""" def __init__(self): super().__init__(channel_a) # 订阅channel_a self.front_numbers = [] self.back_numbers = [] self._lock = threading.Lock() def handle_event(self, event: dict): """处理事件""" if event.get("event_type") == "numbers_updated" and event.get("source") == "module1": data = event.get("data", {}) fronts = data.get("fronts", []) backs = data.get("backs", []) with self._lock: self.front_numbers = fronts self.back_numbers = backs print(f"[EventC] 数据接收成功: 前区{fronts} 后区{backs}") self.show_recommendations(fronts, backs) def show_recommendations(self, fronts, backs): """显示推荐号码""" front_str = ', '.join([str(x).zfill(2) for x in fronts]) back_str = ', '.join([str(x).zfill(2) for x in backs]) tag = f"事件C号码池:前区[{front_str}] 后区[{back_str}]" print(tag) messagebox.showinfo("推荐号码", tag) class ManualInputModel: """增强版手动输入推荐模块""" def __init__(self, root): self.root = root self.root.title("模块1 手动输入") self.front_entries = [] self.back_entries = [] self.saved_front_numbers = [] self.saved_back_numbers = [] self.module1 = Module1() self.event_c_pool = EventCPool() # 正确初始化EventCPool self.event_c_pool.start() self.load_saved_numbers() self.create_input_section("前区", 1, 35, 10, 1) self.create_input_section("后区", 1, 12, 10, 4) save_button = tk.Button(root, text="保存", command=self.save_numbers) clear_button = tk.Button(root, text="清除", command=self.clear_entries) save_button.grid(row=6, column=8, padx=10, pady=10) clear_button.grid(row=6, column=9, padx=10, pady=10) def create_input_section(self, label_text, min_range, max_range, count, row_offset): label = tk.Label(self.root, text=label_text) label.grid(row=row_offset, columnspan=10, pady=(10, 0)) entries = [] for i in range(count): entry = tk.Entry(self.root, width=5) entry.grid(row=row_offset + (i // 5) + 1, column=i % 5, padx=10, pady=5) entries.append(entry) if label_text == "前区": self.front_entries = entries for i, num in enumerate(self.saved_front_numbers): if i < len(entries): entries[i].insert(0, str(num)) else: self.back_entries = entries for i, num in enumerate(self.saved_back_numbers): if i < len(entries): entries[i].insert(0, str(num)) def process_numbers(self, raw_numbers, min_range, max_range): """处理输入号码""" processed = [] seen = set() for num in raw_numbers: try: n = int(num.get().strip()) if n < min_range or n > max_range: messagebox.showwarning("警告", f"号码 {n} 超出范围,已忽略") continue except ValueError: messagebox.showwarning("警告", f"无效号码 {num.get().strip()} 已忽略") continue if n not in seen: seen.add(n) processed.append(n) return processed def save_numbers(self): """保存输入的号码""" front_exclude = self.process_numbers(self.front_entries, 1, 35) back_exclude = self.process_numbers(self.back_entries, 1, 12) with open('saved_numbers.json', 'w') as f: json.dump({ 'front': [entry.get().strip() for entry in self.front_entries], 'back': [entry.get().strip() for entry in self.back_entries] }, f) front_recommend = sorted(list(set(range(1, 36)) - set(front_exclude))) back_recommend = sorted(list(set(range(1, 13)) - set(back_exclude))) result_message = ( f"【前区处理结果】\n" f"原始输入:{[str(x).zfill(2) for x in front_exclude]}\n" f"有效排除:{[str(x).zfill(2) for x in front_exclude]}\n" f"推荐号码({len(front_recommend)}个):{[str(x).zfill(2) for x in front_recommend]}\n\n" f"【后区处理结果】\n" f"原始输入:{[str(x).zfill(2) for x in back_exclude]}\n" f"有效排除:{[str(x).zfill(2) for x in back_exclude]}\n" f"推荐号码({len(back_recommend)}个):{[str(x).zfill(2) for x in back_recommend]}" ) messagebox.showinfo("处理结果", result_message) self.module1.set_module_data(front_recommend, back_recommend) def clear_entries(self): """清除所有输入框的内容""" for entry in self.front_entries + self.back_entries: entry.delete(0, tk.END) def load_saved_numbers(self): """从文件加载已保存的号码""" try: with open('saved_numbers.json', 'r') as f: data = json.load(f) self.saved_front_numbers = [int(num) for num in data['front'] if num.strip().isdigit()] self.saved_back_numbers = [int(num) for num in data['back'] if num.strip().isdigit()] except (FileNotFoundError, json.JSONDecodeError, KeyError): self.saved_front_numbers = [] self.saved_back_numbers = [] def __del__(self): """析构函数,停止事件订阅""" if hasattr(self, 'event_c_pool'): self.event_c_pool.stop() def main(): root = tk.Tk() app = ManualInputModel(root) root.mainloop() if __name__ == "__main__": main() #=============================模块2 组合分析======================================== import pandas as pd from collections import Counter import itertools from tkinter import messagebox, Tk, Event as TkEvent import threading import queue import time from dataclasses import dataclass import chardet # 创建Tkinter根窗口实例 root = Tk() root.withdraw() # 隐藏主窗口 # 全局通信队列 channel_a = queue.Queue() # 主事件通道 response_queue = queue.Queue() # 响应队列 @dataclass class CustomEvent: """自定义事件类,与Tkinter的Event区分""" event_id: int timestamp: float type: str source: str data: dict = None class Module2: """事件A发布者(模块2)""" def __init__(self): self._lock = threading.Lock() self.event_counter = 1 self._setup_response_listener() def _setup_response_listener(self): """启动响应监听线程""" def listener(): while True: try: response = response_queue.get(timeout=1) if response['source'] == 'EventC' and not response['success']: print(f"[模块2] 传输数据失败 - 事件ID {response['event_id']} - 错误: {response.get('error', '未知错误')}") response_queue.task_done() except queue.Empty: continue threading.Thread(target=listener, daemon=True).start() def _publish_event_a(self, event_data): """发布事件A方法""" try: event = CustomEvent( event_id=self.event_counter, timestamp=time.time(), type='A', source="module2", data=event_data ) channel_a.put(event) print(f"[模块2] 事件A发布成功: ID {self.event_counter}") self.event_counter += 1 return True except Exception as e: print(f"[模块2] 事件发布失败: {str(e)}") response_queue.put({ 'event_id': self.event_counter, 'success': False, 'source': 'Module2', 'error': str(e) }) return False def generate_combinations(self, fronts: list, backs: list): """生成号码组合""" valid_fronts = [num for num in fronts if isinstance(num, int) and 1 <= num <= 35] valid_backs = [num for num in backs if isinstance(num, int) and 1 <= num <= 12] if not valid_fronts or not valid_backs: print("[警告] 模块2接收到的数据无效") return [], [] combinations_front = [] combinations_back = [] def format_number(num): return f"{num:02}" # 生成高频号码组合 for i in range(len(valid_fronts)): for j in range(i + 1, len(valid_fronts)): comb = format_number(min(valid_fronts[i], valid_fronts[j])) + \ format_number(max(valid_fronts[i], valid_fronts[j])) if int(comb) <= 35: combinations_front.append(int(comb)) # 生成缺失号码组合 for i in range(len(valid_backs)): for j in range(i + 1, len(valid_backs)): comb = format_number(min(valid_backs[i], valid_backs[j])) + \ format_number(max(valid_backs[i], valid_backs[j])) if int(comb) <= 12: combinations_back.append(int(comb)) # 组合高低位号码 allowed_tens = {0, 1, 2, 3} for ten_digit in allowed_tens: for front in valid_fronts: if front != ten_digit: comb = format_number(ten_digit) + format_number(front) if int(comb) <= 35: combinations_front.append(int(comb)) for back in valid_backs: if back != ten_digit: comb = format_number(ten_digit) + format_number(back) if int(comb) <= 12: combinations_back.append(int(comb)) # 去重并排序 combinations_front = sorted(set(combinations_front)) combinations_back = sorted(set(combinations_back)) # 发布事件A event_data = { "event_type": "module2_recommendation", "data": { "fronts": combinations_front, "backs": combinations_back } } self._publish_event_a(event_data) return combinations_front, combinations_back class EventCPool: """事件处理器(订阅者)""" def __init__(self): self.last_fronts = [] # 初始化 last_fronts self.last_backs = [] # 新增初始化 last_backs self._lock = threading.Lock() self.front_numbers = [] self.back_numbers = [] self._running = True self._setup_event_processor() def stop(self): self._running = False def _setup_event_processor(self): """启动事件处理线程""" def processor(): while self._running: try: event = channel_a.get(timeout=1) self.handle_event(event) channel_a.task_done() except queue.Empty: continue threading.Thread(target=processor, daemon=True).start() print("事件C号码池已启动,正在监听channel_a...") def handle_event(self, event: CustomEvent): # 使用CustomEvent类型提示 """处理事件方法""" if not isinstance(event, CustomEvent) or event.type != 'A' or event.source != "module2": print(f"[事件处理器] 忽略无效事件 - 类型: {event.type}, 来源: {event.source}") return try: data = event.data.get("data", {}) # 提取事件数据 fronts = data.get("fronts", []) backs = data.get("backs", []) with self._lock: # 线程安全操作 self.front_numbers.extend(fronts) self.back_numbers.extend(backs) self.front_numbers = sorted(list(set(self.front_numbers))) self.back_numbers = sorted(list(set(self.back_numbers))) # 发送静默响应 response_queue.put({ 'event_id': event.event_id, 'success': True, 'source': 'EventC' }) # 使用自定义事件传递数据 root.event_generate('<<UpdateGUI>>', when='tail') root.update_idletasks() # 确保事件被处理 # 存储数据供GUI更新使用 self.last_fronts = fronts.copy() # 避免直接引用 self.last_backs = backs.copy() # 避免直接引用 print(f"[事件C号码池] 接收数据成功: 前区{fronts} 后区{backs}") except Exception as e: print(f"[事件处理器] 处理事件失败 - 事件ID: {event.event_id} - 错误: {str(e)}") response_queue.put({ 'event_id': event.event_id, 'success': False, 'source': 'EventC', 'error': str(e) }) class CombinationAnalyzer: """组合分析模块""" def __init__(self, df, model_name="DefaultModel"): self.df = df self.current_draw = df.iloc[-1] self.current_front = self.current_draw['前区号码'] self.current_back = self.current_draw['后区号码'] self.model_name = model_name self.combined_recommendations = [] self.module2 = Module2() def analyze(self): """执行分析""" # 数字频率统计 recent_front_digit_freq_counter = self._count_digit_frequency(self.current_front) frequent_front_numbers_last_draw = self._get_frequent_numbers(recent_front_digit_freq_counter) missing_front_numbers_last_draw = self._get_missing_numbers(recent_front_digit_freq_counter) recent_back_digit_freq_counter = self._count_digit_frequency(self.current_back) frequent_back_numbers_last_draw = self._get_frequent_numbers(recent_back_digit_freq_counter) missing_back_numbers_last_draw = self._get_missing_numbers(recent_back_digit_freq_counter) # 最近50期频率统计 front_freq_counter, back_freq_counter = self._count_recent_occurrences(50) top_frequent_front_numbers_50_draws = self._get_top_frequent_front_numbers(front_freq_counter) bottom_infrequent_back_numbers_50_draws = self._get_bottom_infrequent_back_numbers(back_freq_counter) combinations = self._generate_combinations() recommended_numbers_from_combination = self._get_recommended_numbers(combinations) # 综合推荐 combined_recommendations = list( set(frequent_front_numbers_last_draw).union( missing_front_numbers_last_draw).union( frequent_back_numbers_last_draw).union( missing_back_numbers_last_draw).union( top_frequent_front_numbers_50_draws).union( bottom_infrequent_back_numbers_50_draws)) # 打印结果 self._print_analysis_results( recent_front_digit_freq_counter, frequent_front_numbers_last_draw, missing_front_numbers_last_draw, recent_back_digit_freq_counter, frequent_back_numbers_last_draw, missing_back_numbers_last_draw, front_freq_counter, back_freq_counter, top_frequent_front_numbers_50_draws, bottom_infrequent_back_numbers_50_draws, combinations, recommended_numbers_from_combination, combined_recommendations) # 更新号码池 front_numbers = [int(n) for n in combined_recommendations if 1 <= int(n) <= 35] back_numbers = [int(n) for n in combined_recommendations if 1 <= int(n) <= 12] self.module2.generate_combinations(front_numbers, back_numbers) self.combined_recommendations = combined_recommendations return combined_recommendations def display_recommendations(self, combined_recommendations): front_str = ', '.join([str(x).zfill(2) for x in combined_recommendations if 1 <= int(x) <= 35]) back_str = ', '.join([str(x).zfill(2) for x in combined_recommendations if 1 <= int(x) <= 12]) tag = f"模块2:前区[{front_str}] 后区[{back_str}]" print(tag) messagebox.showinfo("推荐号码", tag, parent=root) def _count_digit_frequency(self, numbers): digits = [] for num in numbers: num_str = f"{int(num):02d}" digits.extend([int(d) for d in num_str]) return Counter(digits) def _get_frequent_numbers(self, freq_counter, top=3): return [f"{num:01d}" for num, _ in freq_counter.most_common(top)] def _get_missing_numbers(self, freq_counter): all_digits = set(range(10)) appeared_digits = set(freq_counter.keys()) missing_digits = all_digits - appeared_digits return [f"{num:01d}" for num in sorted(missing_digits)] def _count_recent_occurrences(self, period=50): recent_draws = self.df.iloc[-period:] front_freq_counter = Counter() back_freq_counter = Counter() for _, draw in recent_draws.iterrows(): front_numbers = draw['前区号码'] back_numbers = draw['后区号码'] front_freq_counter.update(front_numbers) back_freq_counter.update(back_numbers) return front_freq_counter, back_freq_counter def _get_top_frequent_front_numbers(self, front_freq_counter, top=5): return [f"{num:02d}" for num, _ in front_freq_counter.most_common(top)] def _get_bottom_infrequent_back_numbers(self, back_freq_counter, bottom=5): return [f"{num:02d}" for num, _ in back_freq_counter.most_common()[:-bottom - 1:-1]] def _generate_combinations(self): split_digits = [] for num in self.current_front: num_str = f"{int(num):02d}" split_digits.extend([num_str[0], num_str[1]]) for num in self.current_back: num_str = f"{int(num):02d}" split_digits.extend([num_str[0], num_str[1]]) return {''.join(pair) for pair in itertools.product(split_digits, repeat=2)} def _get_recommended_numbers(self, combinations): all_numbers = set(range(1, 36)) generated_numbers = {int(comb) for comb in combinations if 1 <= int(comb) <= 35} recommended_numbers = all_numbers - generated_numbers return [f"{num:02d}" for num in recommended_numbers] def _print_analysis_results(self, *args): ( recent_front_digit_freq_counter, frequent_front_numbers_last_draw, missing_front_numbers_last_draw, recent_back_digit_freq_counter, frequent_back_numbers_last_draw, missing_back_numbers_last_draw, front_freq_counter, back_freq_counter, top_frequent_front_numbers_50_draws, bottom_infrequent_back_numbers_50_draws, combinations, recommended_numbers_from_combination, combined_recommendations ) = args print("=== 前区数字出现频率统计 ===") for digit, count in sorted(recent_front_digit_freq_counter.items()): print(f"{digit}\t{count}") print("\n前区数字频繁推荐(最近一期):") print("【" + " ".join(frequent_front_numbers_last_draw) + "】") print("\n前区缺失的数字(最近一期):") print("【" + " ".join(missing_front_numbers_last_draw) + "】") print("\n=== 后区数字出现频率统计 ===") for digit, count in sorted(recent_back_digit_freq_counter.items()): print(f"{digit}\t{count}") print("\n后区数字频繁推荐(最近一期):") print("【" + " ".join(frequent_back_numbers_last_draw) + "】") print("\n后区缺失的数字(最近一期):") print("【" + " ".join(missing_back_numbers_last_draw) + "】") print("\n=== 最近50期数字出现频率统计 ===") print("前区号码\t出现次数") for num, count in sorted(front_freq_counter.items(), key=lambda item: item[1], reverse=True): print(f"{num}\t{count}") print("\n后区号码\t出现次数") for num, count in sorted(back_freq_counter.items(), key=lambda item: item[1], reverse=True): print(f"{num}\t{count}") print("\n前区号码频繁推荐(最近50期):") print("【" + " ".join(top_frequent_front_numbers_50_draws) + "】") print("\n后区号码低频推荐(最近50期):") print("【" + " ".join(bottom_infrequent_back_numbers_50_draws) + "】") print(f"\n生成的组合数量: {len(combinations)}") print("在00-99中没有组合的数字且在1-35范围内的号码:") print(f"【{' '.join(recommended_numbers_from_combination)}】") print("\n综合推荐号码:") print("【" + " ".join(combined_recommendations) + "】") def detect_file_encoding(file_path): """检测文件编码""" with open(file_path, 'rb') as f: result = chardet.detect(f.read()) return result['encoding'] def read_file(module_name, file_path): """改进的文件读取方法""" try: encoding = detect_file_encoding(file_path) print(f"{module_name}: 检测到文件编码为 {encoding}") df = pd.read_csv(file_path, encoding=encoding) print(f"{module_name}: 数据读取成功") # 列名标准化 df = df.rename(columns={ '开奖期号': '期号', '前1': '前1', '前2': '前2', '前3': '前3', '前4': '前4', '前5': '前5', '后1': '后1', '后2': '后2' }) # 合并号码列 df['前区号码'] = df[['前1', '前2', '前3', '前4', '前5']].values.tolist() df['后区号码'] = df[['后1', '后2']].values.tolist() return df except Exception as e: print(f"{module_name}: 数据读取失败 - {e}") return None def start_threads(): """主线程启动方法""" file_path = 'F:\\超级\\历史数据\\历史数据.csv' df = read_file('模块2:组合分析', file_path) if df is None: return # 初始化组件 event_cpool = EventCPool() analyzer = CombinationAnalyzer(df) # 设置GUI更新事件处理器 def on_gui_update(event): # 确保 EventCPool 实例存在并且 last_fronts 和 last_backs 已正确初始化 if hasattr(event_cpool, 'last_fronts') and hasattr(event_cpool, 'last_backs'): fronts = event_cpool.last_fronts backs = event_cpool.last_backs if fronts is not None and backs is not None: front_str = ', '.join([str(x).zfill(2) for x in fronts]) back_str = ', '.join([str(x).zfill(2) for x in backs]) tag = f"模块2:前区[{front_str}] 后区[{back_str}]" print(tag) messagebox.showinfo("推荐号码", tag, parent=root) else: print("Error: last_fronts 或 last_backs 为 None") else: print("Error: EventCPool 实例缺少 last_fronts 或 last_backs 属性") root.bind('<<UpdateGUI>>', on_gui_update) # 执行分析 recommendations = analyzer.analyze() analyzer.display_recommendations(recommendations) # 等待事件处理完成 time.sleep(2) event_cpool.stop() if __name__ == "__main__": # 先启动主线程 threading.Thread(target=start_threads, daemon=True).start() # 然后运行主循环 root.mainloop() #=======================模块3:跟随分析 ====================================== import threading import queue import pandas as pd import time import random import os import chardet # 定义通信通道 channel_a = queue.Queue() # 模块3 -> 号码池 ack_channel = queue.Queue() # 号码池 -> 模块3 (应答通道) class FollowingAnalyzer: """跟随分析模块(事件A的第三个发布者)""" def __init__(self, df): self.df = df.tail(100).copy() def analyze(self): """执行分析并返回结果""" front_following, back_following = self._analyze_following() front_most, front_least = self._get_recommendations(front_following) back_most, back_least = self._get_recommendations(back_following) # 转换数据类型 front_most = [int(num) for num in front_most] front_least = [int(num) for num in front_least] back_most = [int(num) for num in back_most] back_least = [int(num) for num in back_least] # 打印模块本地分析结果 print("\n=== 模块3分析结果 ===") print(f"前区推荐(多): {front_most}") print(f"前区推荐(少): {front_least}") print(f"后区推荐(多): {back_most}") print(f"后区推荐(少): {back_least}") # 准备发送数据 event_data = { "event_type": "A", "publisher": "模块3", "sequence": 3, "data": { "front_area": front_most + front_least, "back_area": back_most + back_least }, "timestamp": time.time() } # 发送数据到号码池 channel_a.put(event_data) print("\n模块3: 数据已发送到号码池,等待确认...") # 等待应答(5秒超时) try: ack = ack_channel.get(timeout=5) if ack.get("status") == "success": print("模块3: 号码池已成功接收数据") else: print("模块3: 收到异常应答") except queue.Empty: print("模块3: 传输数据失败(未收到应答)") return front_most + back_most def _analyze_following(self): """分析前后区号码的跟随关系""" front_following = defaultdict(Counter) back_following = defaultdict(Counter) for i in range(len(self.df) - 1): current = self.df.iloc[i] next_draw = self.df.iloc[i + 1] for num in current['前区号码']: for fnum in next_draw['前区号码']: front_following[num][fnum] += 1 for num in current['后区号码']: for fnum in next_draw['后区号码']: back_following[num][fnum] += 1 return front_following, back_following def _get_recommendations(self, following_dict, top_n=5): """获取推荐号码""" all_numbers = Counter() for num in following_dict: all_numbers.update(following_dict[num]) most_common = [num for num, _ in all_numbers.most_common(top_n)] appeared = [num for num in all_numbers if all_numbers[num] > 0] least_common = sorted([n for n in appeared if n not in most_common], key=lambda x: all_numbers[x])[:top_n] return most_common, least_common class NumberPool(threading.Thread): """号码池(事件A的订阅者)""" def __init__(self): super().__init__() self.stop_event = threading.Event() self.received_data = [] def run(self): while not self.stop_event.is_set(): try: # 接收数据 event = channel_a.get(timeout=1) # 只处理来自模块3的事件A if event["event_type"] == "A" and event["publisher"] == "模块3": # 显示接收数据 print("\n=== 号码池接收数据 ===") print(f"来自: {event['publisher']}(序列:{event['sequence']})") print(f"前区号码: {event['data']['front_area']}") print(f"后区号码: {event['data']['back_area']}") print(f"接收时间: {time.ctime(event['timestamp'])}") # 存储数据 self.received_data.append(event) # 发送成功应答 ack_channel.put({ "status": "success", "received_time": time.time() }) except queue.Empty: continue def stop(self): self.stop_event.set() class Module3Controller: """模块3控制器""" def __init__(self, file_path): self.file_path = file_path self.interface = Module3DataInterface(file_path) def execute(self): df = self.interface.get_module_data() if df is not None: analyzer = FollowingAnalyzer(df) return analyzer.analyze() return None class Module3DataInterface: """模块3数据接口""" def __init__(self, file_path): self.file_path = file_path def get_module_data(self): try: encoding = detect_encoding(self.file_path) df = pd.read_csv(self.file_path, encoding=encoding) print("模块3: 数据读取成功") df = df.rename(columns={ '开奖期号': '期号', '前1': '前1', '前2': '前2', '前3': '前3', '前4': '前4', '前5': '前5', '后1': '后1', '后2': '后2' }) df['前区号码'] = df[['前1', '前2', '前3', '前4', '前5']].values.tolist() df['后区号码'] = df[['后1', '后2']].values.tolist() return df except Exception as e: print(f"模块3: 数据读取失败 - {e}") return None def detect_encoding(file_path): """检测文件编码""" try: with open(file_path, 'rb') as f: rawdata = f.read(100000) result = chardet.detect(rawdata) print(f"编码检测结果: {result['encoding']} (置信度: {result['confidence']:.1%})") return result['encoding'] or 'gb18030' except Exception as e: print(f"编码检测失败: {str(e)}") return 'gb18030' if __name__ == "__main__": # 启动号码池 pool = NumberPool() pool.start() print("号码池已启动,等待接收数据...") # 运行模块3 controller = Module3Controller('F:\\超级\\历史数据\\历史数据.csv') print("\n模块3开始执行分析...") result = controller.execute() # 等待处理完成 time.sleep(2) # 停止号码池 pool.stop() pool.join() print("\n号码池已停止") # 输出最终汇总 if pool.received_data: print("\n=== 号码池最终数据 ===") for i, data in enumerate(pool.received_data, 1): print(f"\n记录{i}:") print(f"前区: {data['data']['front_area']}") print(f"后区: {data['data']['back_area']}") else: print("\n警告: 号码池未收到任何数据") s = 1 def test(): s += 1 print(s) test() 】
05-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值