CSV文件合并
版本一:只用csv
注意:写入文件时 参数ab表示写入文件的是二进制文件,具体是ab还是a要和前面读的r和rb有关
import csv
file = []
for i in range(2001,2022):
f_i = '/Users/sunmengge/Desktop/scopus_content/content_%d.csv'%i
file.append(f_i)
j = 2001
for k in file: # 循环读取同文件夹下的csv文件
fr = open(k, 'rb').read()
temp = []
temp.append(j)
temp.append(fr)
with open('/Users/sunmengge/Desktop/scopus_content/result.csv', 'ab') as f:
f.write(fr)
j = j+1
print('合并完毕!')
这里,如果写入文件时为:f.writerow(),则括号内最好是列表
版本二:pandas
pandas不如csv好用 或者说csv的ab好用!
否则涉及文件中每列分割符号的问题
列表Counter计数
from collections import Counter
#构建词汇库
file=open(u'/Users/sunmengge/Desktop/scopus_content/scopus_fenci/fenci.csv','rb')
file_cont=file.readlines()
corpus1 = []
for text in file_cont:
words=text.decode().strip().split('|')
for word in list(set(words)):
corpus1.append(word)
#自动计算每一词汇对应的频数!!
counter1 = Counter(corpus1)
##转化成字典形式
dic = dict(counter1)
##!!重点在于输出每一词汇对应的词频数 这也是字典形式应该掌握的语法
##str(terms[ind]) 为某词汇
for i,v in dic.items():
if i ==str(terms[ind]):
count = v
小tips:对列表a的去重为:list(set(a))