# 提取所有需要的数据
data = []
second_data = []
for i in range(1, 121): # tr[1] 到 tr[120]
path = interval_xpath.format(i)
second_path = parity_xpath.format(i)
value = tree.xpath(path)
second_value = tree.xpath(second_path)
if value and second_value: # 如果找到元素
data.append(value[0].text_content().strip())
second_data.append(second_value[0].text_content().strip())
# 计算每个元素及其出现的次数和百分比
for item, count in counter.items():
items_str.append(item)
percentage = (count / total) * 1
percentages.append(percentage)
for second_item, second_count in second_counter.items():
second_items_str.append(second_item)
second_percentage = (second_count / second_total) * 1
second_percentages.append(second_percentage)
# 将items_str中的每个元素转换为整数列表
items_int = [list(map(int, item.split(':'))) for item in items_str]
second_items_int = [list(map(int, item.split(':'))) for item in second_items_str]
odd_even_ratio = random.choices(second_items_sorted, weights=second_percentages_sorted, k=1)[0]
required_odds, required_evens = odd_even_ratio
total_sum_list = [(40, 49), (50, 59),
(60, 69), (70, 79), (80, 89),
(90, 99), (100, 109), (110, 119),
(120, 129), (130, 139), (140, 149)]
total_sum_weights = [0.01, 0.01, 0.06, 0.10, 0.11, 0.20, 0.14, 0.21, 0.11, 0.02, 0.03]
total_sum_result = random.choices(total_sum_list, weights=total_sum_weights, k=1)[0]
start, end = total_sum_result
attempt = 0 # 记录循环次数
while not start <= total_sum <= end or len([num for num in picked_numbers if num % 2 != 0]) != required_odds or len(
[num for num in picked_numbers if num % 2 == 0]) != required_evens:
picked_numbers.clear()
total_sum = 0
if attempt == 500: # 如果循环500次没有符合的数据就跳出
break
for ratio, section in zip(ratios, sections):
for _ in range(ratio):
# 选择奇数或偶数
if len([num for num in picked_numbers if num % 2 != 0]) < required_odds and random.choice(
[True, False]):
# 选择奇数
num = random.choice([n for n in range(section[0], section[1] + 1) if n % 2 != 0])
else:
# 选择偶数
num = random.choice([n for n in range(section[0], section[1] + 1) if n % 2 == 0])
# 确保不重复
while num in picked_numbers:
num = random.choice([n for n in range(section[0], section[1] + 1) if
n % 2 != 0]) if num % 2 != 0 else random.choice(
[n for n in range(section[0], section[1] + 1) if n % 2 == 0])
picked_numbers.append(num)
total_sum += num
attempt += 1 # 新增:循环次数加1
# 提取所有需要的数据
data = []
for i in range(1, 121): # tr[1] 到 tr[120]
path = interval_xpath.format(i)
value = tree.xpath(path)
if value: # 如果找到元素
data.append(value[0].text_content().strip())