如何使用Python在多个csv文件中查找特定的泰语单词并返回包含该单词的文件名列表

7xllpg7q  于 2022-12-06  发布在  Python
关注(0)|答案(1)|浏览(140)

我有喜欢100+文件在目录中,我需要找出哪些文件包含的话,我在泰国寻找
谢谢你
我试过了,但没有用

import pandas as pd
import re
import os

FOLDER_PATH = r'C:\Users\project'

list = os.listdir(FOLDER_PATH)

 def is_name_in_csv(word,csv_file):
  with open(csv_file,"r") as f:
    data = f.read()
  return bool(re.search(word, data))

word = "บัญชีรายรับ"
for csv_file in list:
  if is_name_in_csv(word,csv_file):
    print(f"find the {word} in {csv_file}")

`

cbjzeqam

cbjzeqam1#

你不需要regex,你可以简单地检查word in fileContents是否是list。另外,我把list改成了paths,因为list是一个内置的python关键字。

import os

paths = os.listdir(r'C:\Users\project')

def files_with_word(word:str, paths:list) -> str:
    for path in paths:
        with open(path, "r") as f:
            if word in f.read():
                yield path

#if you need to do something after each found file
for filepath in files_with_word("บัญชีรายรับ", paths):
    print(filepath)

#or if you just need a list
filepaths = [fp for fp in files_with_word("บัญชีรายรับ", paths)]

相关问题