2013-06-19 2 views
1

과제는 파일을 열고 텍스트 파일을 열고 사용 된 모든 단어의 목록을 만드는 것입니다. 파일을 열거 나 읽고 닫을 수는 있지만 분할하려고하면 아래 오류가 발생합니다.Python 3에서 텍스트를 분할하는 방법

이것은 무엇을 의미하며 어떤 제안이 있습니까?

file = open("decl.txt", "r") 
lines = file.readlines() 
text.close() 

# split oliver 
words = re.split('\W+', lines) 

print(words) 

Traceback (most recent call last): 
    File "lab.py", line 18, in <module> 
    words = re.split('\W+', lines) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.py", line 165, in split 
TypeError: expected string or buffer 
+0

왜 텍스트를 닫는? 그게 파일이 될까요? – thefourtheye

답변

2

file.readlines() 모든 라인의 목록을 반환 오류 메시지, 당신은 file.read() 사용해야합니다 파일을 처리 할 때

항상 with를 사용, 자동을 위해 파일을 닫습니다거야 당신. file.read

with open("decl.txt", "r") as f: 
    data = f.read() 
# split oliver 
words = re.split('\W+', data) 

도움말 :

>>> print file.read.__doc__ 
read([size]) -> read at most size bytes, returned as a string. 

If the size argument is negative or omitted, read until EOF is reached. 
Notice that when in non-blocking mode, less data than what was requested 
may be returned, even if no size parameter was given. 
+0

감사합니다 !!! 그건 내 문제를 해결 –

+0

내 테이크 아웃 :'readlines'는 모든 라인의 **리스트 **를 반환합니다. 감사 – thefourtheye

관련 문제