简体   繁体   English

如何在Python 3中分割文字

[英]How to split text in Python 3

My assignment is to open a file and to open a text file and make a list of the all the words used. 我的任务是打开一个文件并打开一个文本文件,并列出所有使用的单词。 I am able to open, read, and close the file, however, when I try to split, I get the following error below. 我可以打开,读取和关闭文件,但是,当我尝试拆分时,出现以下错误。

What does this mean and any suggestions? 这是什么意思和任何建议?

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

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

print(words)

Error Message 错误信息

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

file.readlines() returns a list of all lines, you should use file.read() : file.readlines()返回所有行的列表,您应该使用file.read()

Always use with when handling files, it'll automatically close the file for you. 处理文件时始终with使用,它将自动为您关闭文件。

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

Help on file.read : 关于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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM