You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.7 KiB

import palettable
import csv
from typing import List, Tuple
def read_csv_to_list(csv_file: str) -> List[Tuple[str, int]]:
"""
从CSV文件读取数据并转换为list[tuple[str, int]]
Args:
csv_file: CSV文件路径
Returns:
List[Tuple[str, int]]: 包含(内容, 频率)的列表
"""
result = {}
try:
with open(csv_file, 'r', encoding='utf-8') as file:
# 创建CSV读取器
csv_reader = csv.reader(file)
# 跳过标题行(如果有)
headers = next(csv_reader, None)
for row in csv_reader:
content = row[0].strip() # 内容列
frequency = int(row[1]) # 频率列(转换为整数)
result[content] = frequency
except FileNotFoundError:
print(f"错误:文件 {csv_file} 未找到")
except ValueError as e:
print(f"错误:频率值转换失败 - {e}")
except Exception as e:
print(f"读取文件时发生错误:{e}")
return result
def trans_list_to_csv(ls: List[Tuple[str, int]], csv_file: str) -> None:
"""
将list[tuple[str, int]]转换并保存为CSV文件
Args:
ls: 包含(内容, 频率)的列表
"""
try:
with open(csv_file, 'w', encoding='utf-8', newline='') as file:
csv_writer = csv.writer(file)
# 写入标题行
csv_writer.writerow(['内容', '频率'])
# 写入数据行
for content, frequency in ls:
csv_writer.writerow([content.replace(",", "_"), frequency])
print(f"数据已成功保存到 {csv_file}")
except Exception as e:
print(f"写入文件时发生错误:{e}")