[英]Python: Creating a file list from a directory of .txt files
我正在嘗試從 .txt 文件的目錄中加載語料庫,然后創建一個文檔列表。
我認為它會很簡單,但是當我運行它時沒有任何反應,我錯過了什么嗎?
import os.path
import re
import glob
def load_data_from_dir(path):
file_list = glob.glob('/transcripts/*.txt')
# create document list:
documents_list = []
for filename in file_list:
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
f.close()
documents_list.append(text)
print("Total Number of Documents:",len(documents_list))
return documents_list
確保正確縮進 python 中的代碼。 另外,檢查代碼的路徑。 要么給出絕對路徑,要么給出相對路徑。 不過,絕對路徑可以完美運行。
import os.path
import re
import glob
def load_data_from_dir():
file_list = glob.glob('./transcripts/*.txt')
# create document list:
documents_list = []
for filename in file_list:
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
documents_list.append(text)
print("Total Number of Documents:",len(documents_list))
return documents_list
load_data_from_dir()
您的代碼中有一些錯誤。
load_data_from_dir
) 正文沒有縮進。 縮進 function 正文中的所有行(直到您的 return 語句)with
構造打開的文件不應顯式關閉。 刪除f.close()
如果這是一個單獨的模塊並且您只運行 function。 然后什么都不會發生。 您需要確保將其稱為 function。 所以添加
if __name__ == '__main__': load_data_from_dir(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.