我正在嘗試撰寫一個函式length_n(file_name, n),它回傳file_name長度為 n 的(txt 檔案)中的單詞串列。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
uj5u.com熱心網友回復:
你不能這樣做:
file=open('file_name','r')
Python 嘗試查找“file_name”檔案,但我很確定它不存在。
這是解決方案:
file=open(f'{file_name}.txt','r') # you can remove '.txt' if you don't need it
#OR
file=open(file_name,'r') # or simply just this
uj5u.com熱心網友回復:
我這樣修改了你的代碼,
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=[]
with open(f'{file_name}','r') as file: # We can't use file = because it doesn't read it is a parameter of length_n. Then we should use formatter or file = open(file_name,'r').
lines=file.read()
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
當我們使用 with open(f'file_name','r') 作為檔案時,它只是在程式關閉后關閉檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/341241.html
