2013-06-19 42 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,它会自动关闭该文件您。

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

帮助上file.read

>>> 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