2016-06-25 4 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), 플래그에서 = re.IGNORECASE) 라인 (182), 서브 리턴 _compile (패턴, 플래그) .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() 

항상 열려있는 파일을 닫아야합니다.