import csv with open(r'd:\天龙八部-网络版.txt', 'r', encoding='utf8') as fr: text = fr.read() count_dict = {} for char in text: if char != ' ' and char != '\n': # 不统计空格和换行符 if char in count_dict: count_dict[char] += 1 else: count_dict[char] = 1 with open(r'd:\天龙八部-汉字统计.csv', 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerow(['字符', '出现次数']) # 写入表头 for char, count in count_dict.items(): writer.writerow([char, count])输出结果是保存在txt文件里的,不是csv文件
时间: 2023-12-31 11:05:24 浏览: 51
这段代码输出结果保存在 txt 文件而不是 csv 文件的原因是因为在打开文件时,你使用了 `.csv` 扩展名,但实际上你保存的文件路径是 `.txt` 文件。你需要将保存结果的文件路径改为 `.csv` 才能将结果保存为 csv 格式。修改代码如下:
```
import csv
with open(r'd:\天龙八部-网络版.txt', 'r', encoding='utf8') as fr:
text = fr.read()
count_dict = {}
for char in text:
if char != ' ' and char != '\n': # 不统计空格和换行符
if char in count_dict:
count_dict[char] += 1
else:
count_dict[char] = 1
with open(r'd:\天龙八部-汉字统计.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['字符', '出现次数']) # 写入表头
for char, count in count_dict.items():
writer.writerow([char, count])
```
注意:你需要将保存结果的文件路径改为 `.csv` 扩展名,而不是 `.txt`。
阅读全文