2016-06-25 14 views
0

感情分析を行っていますが、否定と句読点の間にすべての単語にNOTを追加したいと思います。感情分析Python TypeError:期待される文字列またはバイト様オブジェクト

import re 


fin=open("aboveE1.txt",'r', encoding='UTF-8') 

transformed = re.sub(r'\b(?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint)\b[\w\s]+[^\w\s]', 
    lambda match: re.sub(r'(\s+)(\w+)', r'\1NEG_\2', match.group(0)), 
    fin, 
    flags=re.IGNORECASE) 

トレースバック(最新の呼び出しの最後):私は、次のコードを行っております ライン14、 flagsに= re.IGNORECASE) ライン182、サブリターン_compile(パターン、flagsに).SUB( repl、string、count) TypeError:予期される文字列またはバイトのようなオブジェクト

このエラーを解決する方法はわかりません。手伝って頂けますか?

答えて

0

re.subはファイルオブジェクトではなく文字列を取ります。ドキュメントhere

import re 

fin=open("aboveE1.txt",'r', encoding='UTF-8')  
transformed = '' 

for line in fin: 
    transformed += re.sub(r'\b(?:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint)\b[\w\s]+[^\w\s]', 
    lambda match: re.sub(r'(\s+)(\w+)', r'\1NEG_\2', match.group(0)), 
    line, 
    flags=re.IGNORECASE) 
    # No need to append '\n' to 'transformed' 
    # because the line returned via the iterator includes the '\n' 

fin.close() 

また、必ず開いているファイルを閉じてください。

関連する問題