python常用查操作
格式化输出字符串
print('i am {0}, my age is {1}'.format('Tom',18))
i am Tom, my age is 18
转为集合类型
a = [1,2,4,2,1]
set(a) # result: {1,2,4}
排序函数
a = [1,4,2,3,1]
sorted(a, reverse = Ture) # result: [4,3,2,1,1]
正则表达式
\. 可以查找英文点号
\d可以查找一个数字
\d+可以查找多个数字
统计表格中内容出现的次数
# encoding=utf-8
import openpyxl
wb = openpyxl.Workbook()
wb = openpyxl.load_workbook('copy1.xlsx') # Excel名
sh = wb['keyword'] # sheet名
'''
换一种写法
sheet=wb.get_sheet_by_name(xl_sheet_names[0]) # 序号为0的sheet
row=sheet.max_row # 得到行数
'''
cons=[] # 将所有数据append成一个list
for cases in list(sh.rows)[1:9240]: # 行数,也可以通过代码来带入
case_D = cases[4].value # 关键词所在的列
cons.append(case_D)
result_new = []
res2 = []
for con in cons:
fenci = con.strip().split('; ') # 假定关键词是以分号隔开
result_new.append(fenci)
new = sum(result_new,[])
res2.append(new)
#print(res2) # res2的形式是 [['aaa','bbb','abc']]
import collections
dic = collections.Counter(res2[0])
f1 = open('关键词及次数.txt','w',encoding = 'utf-8')
# 将关键词和次数写入txt文件
# 写入Excel更好,见下一段代码
for key in dic:
f1.write(str(key) +"\t"+ str(dic[key])+"\n")
print(key,dic[key])
f1.close()
from openpyxl import Workbook
workbook = Workbook()
i=1
# 默认sheet
sh = workbook.active
sh.title = "count"
for key in dic:
sh.cell(row=i, column=1, value=str(key))
sh.cell(row=i, column=2, value=str(dic[key]))
i+=1
workbook.save(r'name.xlsx')
接下来就是愉快的分析啦。
over is Over——Lee