Python2.7で以下のプログラムを使って日本語テキストを分割し、ファイル出力しようと思ったのですが、
Python
1# -*- coding: utf-8 -*- 2import os 3import sys 4import codecs 5sys.stdout=codecs.getwriter('utf-8')(sys.stdout) 6 7files=os.listdir('./') 8files.pop(0) 9files.pop(0) 10 11i=0 12for file in files: 13 if i%2==1: 14 filename=file.replace('.txt','') 15 f=codecs.open(file,'r','sjis') 16 anum=0 17 18 source=[] 19 for line in f: 20 line=line.encode('utf-8') 21 source.append(line.decode('utf-8')) 22 f.close() 23 24 name=str(anum)+'.txt' 25 f=open(name,'w') 26 for line in source: 27 if u'\ID\' in line: 28 f.close() 29 anum+=1 30 name=str(filename)+'/'+str(anum)+'.txt' 31 f=codecs.open(name,'w','sjis') 32 f.write(line.decode('utf-8')) 33 f.close() 34 i+=1
何度かはうまく行ったのですが、最近は以下のようなエラーが出てうまく動きません。
Traceback (most recent call last): File "bunkatsu.txt", line 19, in <module> for line in f: File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 687, in next return self.reader.next() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 618, in next line = self.readline() UnicodeDecodeError: 'shift_jis' codec can't decode bytes in position 32-33: illegal multibyte sequence
色々なサイトを見て自分でも調べましたが、どうしても解決できないため質問させていただきました。
どこに問題があって、どうすれば解決できるのか、ご教授いただければ幸いです。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/10/25 03:22