【发布时间】:2021-10-26 03:06:10
【问题描述】:
我试图编写一个函数length_n(file_name, n),它返回file_name(一个txt文件)中长度为n的单词列表。 file_name 将是包含单词列表的文件的名称。出于某种原因,当我测试我的代码时,open 操作没有成功打开我的文本文件。有谁知道为什么?另外,我是否正确使用了.read 和.split 方法?非常感谢!
def length_n(file_name,n):
#the list of words will be called
l1=[]
#the list of words with the length of n will be called
l2=[]
file=open('file_name','r')
#the individual lines are
lines=file.read()
#split the content into words
l1=lines.split("")
length=len(l1)
for i in range (0,length):
l=len(l1[i])
if l==n:
l2.append(l1[i])
return l2
【问题讨论】:
-
“打开”操作没有成功打开我的文本文件是什么意思?您收到错误消息吗?如果有,是什么?