判断csv某一列是否含有关键词,有则取值1,没有则取值0
时间: 2024-04-30 17:23:47 浏览: 13
以下是Python代码示例:
```python
import csv
# 关键词
keyword = 'apple'
# 读取csv文件
with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
# 获取表头
header = next(reader)
# 获取目标列索引
target_col_index = header.index('column_name')
# 写入新文件
with open('result.csv', 'w', newline='') as resultfile:
writer = csv.writer(resultfile)
# 写入表头
writer.writerow(['column_name', 'result'])
# 遍历每一行
for row in reader:
# 判断目标列是否包含关键词
if keyword in row[target_col_index]:
writer.writerow([row[target_col_index], '1'])
else:
writer.writerow([row[target_col_index], '0'])
```
其中,需要修改的部分是`keyword`和`column_name`,分别表示关键词和目标列的列名。最终结果将保存在`result.csv`文件中,包含两列:目标列的值和结果(0或1)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)