检测excel文件中这一列的所有的变量名在.c文件中是否存在,并输出excel
时间: 2024-05-15 09:15:31 浏览: 14
文件中每个变量名对应的存在情况。
这个任务可以通过以下步骤完成:
1. 从excel文件中读取需要检测的变量名所在的列,保存到一个列表中。
2. 读取.c文件内容,并将其中的变量名保存到一个字典中,字典的键为变量名,值为True。
3. 遍历步骤1中保存的变量名列表,对于每个变量名,在字典中查找是否存在对应的键。如果存在,将该变量名在excel文件中的行号和存在情况(存在/不存在)保存到一个列表中。
4. 将步骤3中保存的结果输出到excel文件中,作为新的一列。
以下是一个示例代码,用于实现这个任务:
```python
import openpyxl
# 读取excel文件中需要检测的变量名所在的列
def read_excel_column(filename, sheetname, column):
wb = openpyxl.load_workbook(filename)
sheet = wb[sheetname]
values = []
for cell in sheet[column]:
values.append(cell.value)
return values
# 读取.c文件内容,并将其中的变量名保存到一个字典中
def read_c_file(filename):
variables = {}
with open(filename, 'r') as f:
for line in f:
words = line.split()
for word in words:
if word.isalpha():
variables[word] = True
return variables
# 检测变量名在.c文件中是否存在,并保存结果到列表中
def check_variables(variables, c_variables):
result = []
for i, var in enumerate(variables):
if var in c_variables:
result.append([i+1, '存在'])
else:
result.append([i+1, '不存在'])
return result
# 将检测结果保存到excel文件中
def save_excel(filename, sheetname, column, result):
wb = openpyxl.load_workbook(filename)
sheet = wb[sheetname]
for i, value in enumerate(result):
sheet[column+str(i+1)] = value[1]
wb.save(filename)
# 测试
if __name__ == '__main__':
# 读取excel文件中需要检测的变量名
variables = read_excel_column('test.xlsx', 'Sheet1', 'A')
# 读取.c文件中的变量名
c_variables = read_c_file('test.c')
# 检测变量名在.c文件中是否存在
result = check_variables(variables, c_variables)
# 将检测结果保存到excel文件中
save_excel('test.xlsx', 'Sheet1', 'B', result)
```
在运行以上代码之前,请确保已经安装了openpyxl模块,可以通过以下命令安装:
```
pip install openpyxl
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)