优化这段代码import os import xlwt path = "../../pics/testtxt/" txts = os.listdir(path) tags=[] a = [] for txt in txts: position = path + txt with open(position, errors='ignore') as f: data = f.read() for i in data.split(', '): tags.append(i) file = xlwt.Workbook(encoding='utf-8') sheet1 = file.add_sheet('sheet1', cell_overwrite_ok=True) sheet1.write(0, 0, 'tag') sheet1.write(0, 1, 'count') tags_set = set(tags) tag_dict = {} i = 0 for item in tags_set: tag_num = tags.count(item) tag_dict[item] = tag_num row = 1 for key, value in tag_dict.items(): sheet1.write(row,0,key) sheet1.write(row, 1, value) file.save('/home/cheny/mnt/pics/tags_count.xls')
时间: 2024-01-25 15:04:43 浏览: 120
在pycharm中导入xlrd和xlwt.模块具体操作.docx
好的,下面是我对你的代码进行了优化:
```python
import os
import xlwt
path = "../../pics/testtxt/"
txts = os.listdir(path)
# 统计所有标签
tags = []
for txt in txts:
position = os.path.join(path, txt)
with open(position, errors='ignore') as f:
data = f.read()
tags.extend(data.split(', '))
# 统计标签数量
tag_dict = {}
for tag in set(tags):
tag_dict[tag] = tags.count(tag)
# 将标签数量写入 Excel 文件
file = xlwt.Workbook(encoding='utf-8')
sheet1 = file.add_sheet('sheet1', cell_overwrite_ok=True)
sheet1.write(0, 0, 'tag')
sheet1.write(0, 1, 'count')
for row, (key, value) in enumerate(tag_dict.items(), start=1):
sheet1.write(row, 0, key)
sheet1.write(row, 1, value)
file.save('/home/cheny/mnt/pics/tags_count.xls')
```
优化后的代码使用了更加简洁的写法,同时也对变量名进行了修改,使其更加符合 Python 的命名规范。这段代码会统计指定目录下所有 `.txt` 文件中的标签并计算标签数量,然后将结果写入名为 `tags_count.xls` 的 Excel 文件中。你可以根据需要修改目录和文件名。
阅读全文