【发布时间】:2021-07-26 19:11:57
【问题描述】:
我是 python 新手,并试图使用我的代码来理解具有文本的 csv 文件的模式/上下文。我的代码能够一次对一个文件执行此操作。我希望它遍历目录中的多个 csv 文件并获取上下文
import pandas as pd
def search_multiple_strings_in_file(file_name, list_of_strings):
"""Get line from the file along with line numbers, which contains any string from the list"""
line_number = 0
list_of_results = []
# Open the file in read only mode
with open("Sandrasales.csv", 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
line_number += 1
# For each line, check if line contains any string from the list of strings
for string_to_search in list_of_strings:
if string_to_search in line:
# If any string is found in line, then append that line along with line number in list
list_of_results.append((string_to_search, line_number, line.rstrip()))
# Return list of tuples containing matched string, line numbers and lines where string is found
return list_of_results
# search for given strings in the file 'sample.txt'
matched_lines = search_multiple_strings_in_file('SandraSales.csv', ['renewal','provision','annual limit'])
print('Total Matched lines : ', len(matched_lines))
for elem in matched_lines:
print('Word = ', elem[0], ' :: Line Number = ', elem[1], ' :: Line = ', elem[2])
假设我的文件夹/目录是 C:\Users\jj\Desktop\analysis,所有 csv 文件都在其中。
【问题讨论】: