【发布时间】:2019-03-14 16:39:50
【问题描述】:
我有一个代码可以检测目录中文件的语言。但是在提到扩展名的类型时,我如何检测目录中所有文件扩展名的语言(例如:- .pdf、.xlsx、.docx 等),而不仅仅是代码中提到的 .txt 文件。附上代码供参考。我想知道如何使用 glob 和 os.walk 来做到这一点。
import csv
from fnmatch import fnmatch
try:
from langdetect import detect
except ImportError:
detect = lambda _: '<dunno>'
import os
rootdir = '.' # current directory
extension = '.txt'
file_pattern = '*' + extension
with open('output.csv', 'w', newline='', encoding='utf-8') as outfile:
csvwriter = csv.writer(outfile)
for dirpath, subdirs, filenames in os.walk(os.path.abspath(rootdir)):
for filename in filenames:
if fnmatch(filename, file_pattern):
lang = detect(os.path.join(dirpath, filename))
csvwriter.writerow([dirpath, filename, lang])
【问题讨论】:
-
如果你的意思是你写的:“所有”文件扩展名:只需将
txt替换为*。但我_猜_你的意思是“不止一个文件扩展名,即这个列表而不是.txtonly:['.pdf', '.xlsx', '.docx']”。对吗?
标签: python file-extension os.walk language-detection