def read_excel(file_path1,file_path2): df1 = pd.read_excel(file_path1) df2 = pd.read_excel(file_path2) return df1,df2
时间: 2024-02-09 13:19:52 浏览: 73
这是一个读取Excel文件的函数,函数名为read_excel,有两个参数file_path1和file_path2,分别表示要读取的两个Excel文件的路径。在函数体中,使用pandas库的read_excel函数读取这两个Excel文件,并将读取结果分别赋值给df1和df2。最后,通过return语句将df1和df2返回给函数调用者。
相关问题
检查一下代码:coding=utf-8 import pandas as pd import os from openpyxl import load_workbook 存放要合并数据的文件夹路径 path = "C:/Users/**/export/data/" result_file = "result.xlsx" def get_excels(): """获取当前文件夹下所有excel文件名""" xlsx_names = [x for x in os.listdir(path) if x.endswith(".xlsx")] return xlsx_names def get_sheets(first_excel_path): """获取指定excel文件的所有sheet名""" xl = pd.ExcelFile(first_excel_path) sheet_names = xl.sheet_names return sheet_names def merge_files(): # 获取所有excel文件名 excels = get_excels() # 获取第一个excel文件的路径 first_excel_path = os.path.join(path, excels[0]) # 获取第一个excel文件的所有sheet名 sheets = get_sheets(first_excel_path) # 以第一个excel文件为基础创建一个新的excel:result shutil.copyfile(first_excel_path, result_file) for sheet in sheets: print(sheet) # 读取当前结果文件当前sheet df1 = pd.read_excel(result_file, sheet_name=sheet) # 多个excel文件中读取同名sheet中的数据并合并 for excel in excels[1:]: each_excel_path = os.path.join(path, excel) xl = pd.ExcelFile(each_excel_path) df2 = xl.parse(sheet) df1 = pd.concat([df1, df2], axis=0, ignore_index=True) # 将合并后的数据以追加的模式写入到新的excel的each_sheet中 writer = pd.ExcelWriter(result_file, engine='openpyxl') book = load_workbook(result_file) writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets) df1.to_excel(writer, sheet_name=sheet, index=False, header=False) writer.save() if name == 'main': merge_files()
这段代码的作用是将指定文件夹下的多个Excel文件中的同名Sheet进行合并,并将合并后的数据写入到一个新的Excel文件中。其中,使用了pandas库和openpyxl库来进行Excel文件的读写和操作。代码的主要流程如下:
1. 定义了函数get_excels()来获取指定文件夹下所有Excel文件的文件名。
2. 定义了函数get_sheets(first_excel_path)来获取指定Excel文件的所有Sheet名。
3. 定义了函数merge_files()来执行合并操作。首先,获取所有Excel文件名,并通过第一个Excel文件的路径来获取第一个Excel文件的所有Sheet名。然后,以第一个Excel文件为基础,创建一个新的Excel文件,并将第一个Excel文件的数据复制到新的Excel文件中。接着,遍历所有Sheet,使用pd.read_excel()方法读取当前结果文件当前Sheet的数据。然后,遍历所有Excel文件(除第一个Excel文件外),使用pd.ExcelFile()方法读取同名Sheet中的数据,并使用pd.concat()方法将数据合并到当前Sheet的数据中。最后,使用pd.ExcelWriter()方法将合并后的数据以追加的模式写入到新的Excel文件的每个Sheet中。
4. 在main函数中调用merge_files()函数来执行合并操作。
优化代码import os import re import pandas as pd from pandas import DataFrame lst1=[] lst2=[] path1 = r'D:\C-cn' path2 = r'D:\C-en' files1 = os.listdir(path1) files2 = os.listdir(path2) lst1=[] lst2=[] reg1=re.compile(r"[^。?!…]*[。?!……]") reg2=re.compile(r'.*\.[\n ]') df1 = [] df2 = [] for i in range(0,39): domain=os.path.abspath(r'D:\C-cn') file1=os.path.join(domain,files1[i]) fn = open(str(file1),encoding='gbk') f1 = fn.readlines() #print(f1) for line in f1: line=line.rstrip('\n') if "。" not in line: lst1.append(line) else: lis=reg1.findall(line) for j in lis: lst1.append(j) data1=DataFrame({"Chinese":lst1}) df1.append(data1) df1 = pd.concat(df1) df1.to_excel("Chinese.xlsx",index="false") for i in range(0,39): domains=os.path.abspath(r'D:\C-en') file2=os.path.join(domains,files2[i]) ft = open(str(file2),encoding='gbk') f2 = ft.readlines() print(f2) for line in f2: if "." not in line: line=line.rstrip("\n") lst2.append(line) else: liss=line.split(". ") for j in liss: j=j+"." lst2.append(j) data2=DataFrame({"English":lst2}) df2.append(data2) df2 = pd.concat(df2)# 合并所有数据 df2.to_excel("English.xlsx",index="false")
这段代码可以进行一些优化,包括:
1. 将重复的代码封装成函数,避免重复代码。
2. 不需要在每次迭代时都重新初始化 `lst1` 和 `lst2` 列表,可以将其初始化放在循环外面。
3. 在使用 `pandas` 库时,最好使用 `read_csv()` 函数和 `to_csv()` 函数,而不是 `DataFrame()` 和 `to_excel()` 函数。
下面是优化后的代码:
```python
import os
import re
import pandas as pd
def get_sentences(file_path, regex):
with open(file_path, encoding='gbk') as f:
lines = f.readlines()
sentences = []
for line in lines:
line = line.rstrip('\n')
if "。" not in line:
sentences.append(line)
else:
lis = regex.findall(line)
for j in lis:
sentences.append(j)
return sentences
def get_english_sentences(file_path):
with open(file_path, encoding='gbk') as f:
lines = f.readlines()
sentences = []
for line in lines:
if "." not in line:
line = line.rstrip("\n")
sentences.append(line)
else:
liss = line.split(". ")
for j in liss:
j = j + "."
sentences.append(j)
return sentences
path1 = r'D:\C-cn'
path2 = r'D:\C-en'
files1 = os.listdir(path1)
files2 = os.listdir(path2)
reg1 = re.compile(r"[^。?!…]*[。?!……]")
reg2 = re.compile(r'.*\.[\n ]')
lst1 = []
for i in range(0, 39):
file1 = os.path.join(path1, files1[i])
lst1 += get_sentences(file1, reg1)
lst2 = []
for i in range(0, 39):
file2 = os.path.join(path2, files2[i])
lst2 += get_english_sentences(file2)
df1 = pd.DataFrame({"Chinese": lst1})
df1.to_csv("Chinese.csv", index=False)
df2 = pd.DataFrame({"English": lst2})
df2.to_csv("English.csv", index=False)
```
这里将中文和英文的句子分别存储到了 `Chinese.csv` 和 `English.csv` 文件中,以便后续的处理和分析。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)