python 读写文件包含多种编码格式的解决方式

yipeiwu_com5年前Python基础

今天写一个脚本文件,需要将多个文件中的内容汇总到一个txt文件中,由于多个文件有三种不同的编码方式,读写出现错误,先将解决方法记录如下:

# -*- coding: utf-8 -*-
import wave
import pylab as pl
import numpy as np
import pandas as pd
import os
import time
import datetime
import arrow
import chardet
import sys 
reload(sys) 
sys.setdefaultencoding('utf8') 
os.chdir("F:/new_srt")


#get words of srt file
###########################################
def get_word():
 path = "F:/new_srt"
 filelist = os.listdir(path)
 for files in filelist:
  print files
  encoding = chardet.detect(open(files,'r').read())['encoding']
  if encoding == 'utf-8':
   data=pd.read_csv(files,encoding="utf-8",sep='\r',header=None)
  elif encoding == 'GB2312':
   try:
    data=pd.read_csv(files,encoding="gbk",sep='\r',header=None)
   except UnicodeDecodeError:
    data=pd.read_csv(files,encoding="utf-8",sep='\r',header=None)
  elif encoding == 'UTF-8-SIG':
   data=pd.read_csv(files,encoding="UTF-8-SIG",sep='\r',header=None)
  else:
   print 'this is an error about %s' % files 

  data_new=pd.DataFrame(np.reshape(data.values, (-1,3)))
  data_new.columns=['index','timecut','content']
  filename = os.path.splitext(files)[0]  #filetype = os.path.splitext(files)[1]
  with open('F:/result.txt', 'a') as file:
   file.write(str(filename)+' ' )
   for item in data_new['content']:
    file.write(item.decode("utf-8") +' ') #s=s.decode("utf-8") 
   file.write('\n')


if __name__ == '__main__':
 get_word()

以上这篇python 读写文件包含多种编码格式的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python字符串编码识别模块chardet简单应用

python的字符串编码识别模块(第三方库): 官方地址: http://pypi.python.org/pypi/chardet import chardet import...

Python中Collections模块的Counter容器类使用教程

Python中Collections模块的Counter容器类使用教程

1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict、set、list、tuple以外的一些特殊的容器类型,分别是: Order...

浅谈python的输入输出,注释,基本数据类型

1.输入与输出 python中输入与输出函数为:print、input help() 帮助的使用:help() help(print) print(value, ..., sep=...

Python实现以时间换空间的缓存替换算法

缓存是指可以进行高速数据交换的存储器,它先于内存与CPU交换数据,因此速度很快。缓存就是把一些数据暂时存放于某些地方,可能是内存,也有可能硬盘。 在使用Scrapy爬网站的时候,产生出来...

Python实现快速计算词频功能示例

本文实例讲述了Python实现快速计算词频功能。分享给大家供大家参考,具体如下: 这几天看到一位同事的代码,方法如下: def cut_word(body): temp_dict...