1.1读取txt
vocabs=[]
with open(“D:/vocab_init.txt”, “r”) as f:
for line in f.readlines():
line = line.strip(‘\n’) #去掉列表中每一个元素的换行符
#print(line)
vocabs.append(line)
1.2 写入txt
final_vocabs = [‘1’,‘2’]
file = open(‘D:/vocab.txt’, ‘w’)
for i in range(len(final_vocabs)):
s = str(final_vocabs[i])+ ‘\n’
file.write(s)
file.close()
1.3 pd 读取csv
import pandas as pd
import csv
train_file=‘D:/train.csv’
traindata=pd.read_csv(train_file)
2.1 pd读取tsv
import pandas as pd
import csv
train_file=‘D:/28.tsv’
traindata=pd.read_csv(train_file, sep=‘\t’,header=None)
2.2 pd写入tsv
import pandas as pd
import csv
final_result= [1,2]
result = pd.DataFrame(final_result)
result.to_csv(‘D:/28.tsv’, sep=‘\t’, index=False, header=False, quoting=csv.QUOTE_NONE)
2.3 pd读取excel
train_file=“D:/tianchi .xlsx”
traindata=pd.read_excel(io=train_file)
2.3.1 读取excel sheet
datas = pd.read_excel(io=train_file,sheet_name=‘开放信息’)
3.1 关于UnicodeDecodeError: ‘gbk’ codec can’t decode byte的解决办法
将with open(file) as f: 改成 with open(file, ‘r’, encoding=‘utf-8’) as f:
3.2 Excel xlsx file; not supported
原因是最近xlrd更新到了2.0.1版本,只支持.xls文件。所以pandas.read_excel(‘xxx.xlsx’)会报错。
可以安装旧版xlrd,在cmd中运行:
pip uninstall xlrd
pip install xlrd==1.2.0
也可以用openpyxl代替xlrd打开.xlsx文件:
df=pandas.read_excel(‘data.xlsx’,engine=‘openpyxl’)