import csv with open(r'd:\天龙八部-网络版.txt','r',encoding='utf8') as fr: text=fr.read() count_dict = {} for ch in text: 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:\天龙八部-汉字统计.txt', 'w', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['字符', '出现次数']) # 写入表头 for char, count in count_dict.items(): writer.writerow([char, count])为什么这个代码输出没有结果
时间: 2024-03-24 10:35:41 浏览: 93
这个代码输出没有结果是因为你使用了 csv.writer 来写入数据,但是你没有将数据写入到 csv 文件中。你需要在循环中将每个字符和它的出现次数写入到文件中。你可以使用 writerow() 方法将数据写入到 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 文件时,需要使用 newline='' 参数。这个参数可以避免在 Windows 系统上出现额外的空行。另外,你也需要将文件扩展名改为 .csv。
阅读全文