langdetect python编写文件名、目录和语言的csv

2024-09-22 22:29:05 发布

您现在位置:Python中文网/ 问答频道 /正文

如何创建循环手术室步行()查找所有“.txt”文件并创建具有三个字段的输出文件.csv 目录,文件名,语言?在

我可以使用print来获取文件名和目录,但我不知道如何将它们放入csv中。 另外,我可以使用langdetect(from langdetect import detectdetect("001.txt")获得语言名称,但是我被困在下面的循环问题上。在

示例

Directory  Filename Language
/c/xx      001      en
/c/xx/y    001      fr

代码

^{pr2}$

过滤器文件


Tags: 文件csvfromimport目录txt名称语言
1条回答
网友
1楼 · 发布于 2024-09-22 22:29:05

如果您需要检查子目录中的文件以及当前目录中的文件,这样做是一个很好的方法。在

它使用os.walk遍历目录结构,使用fnmatch.fnmatch进行(简单)文件名匹配。在

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])

相关问题 更多 >