1

我的任务是打开一个文件并打开一个文本文件并列出所有使用的单词。我能够打开、读取和关闭文件,但是,当我尝试拆分时,我收到以下错误。

这是什么意思和任何建议?

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
4

1 回答 1

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.
于 2013-06-19T23:46:58.197 回答