厉害!普通人借助大模型也可以成为Python大神
作者:憨憨
今天学习了一下用大模型来学习一下写代码。
写完后,我让我程序员朋友给看了看,
结果是能用,并且还知道抛出异常。
不得不说,大模型的兴起让程序员感到了危机。
高喊!
普通人借助大模型也可以成为Python大神
以下是用deepseek生成的,指令如下:
现在你是一名资深Python程序员,请帮我用Python语言来写一段程序。该程序主要功能是:
第一步,从Linux服务器指定目录下的指定文件遍历读取字符串,文件是CSV格式的,读取的是第一列
第二步,将读取的字符串去指定目录下面搜索包含该字符串的文件,并把找到的文件路径写到日志里边
deepseek回答:
import os
import csv
import argparse
from datetime import datetime
def read_csv_first_columns(csv_directory):
"""
从指定目录的所有CSV文件中读取第一列内容
返回去重后的字符串集合
"""
search_strings = set()
# 遍历目录下所有CSV文件
for filename in os.listdir(csv_directory):
if not filename.lower().endswith('.csv'):
continue
filepath = os.path.join(csv_directory, filename)
try:
with open(filepath, 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row: # 跳过空行
search_str = row[0].strip()
if search_str:
search_strings.add(search_str)
except Exception as e:
print(f"Error processing {filepath}: {str(e)}")
return search_strings
def search_string_in_files(search_dir, search_string):
"""
在指定目录递归搜索包含目标字符串的文件
返回匹配的文件路径列表
"""
matched_files = []
for root, _, files in os.walk(search_dir):
for filename in files:
filepath = os.path.join(root, filename)
try:
with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
if search_string in f.read():
matched_files.append(os.path.abspath(filepath))
except Exception as e:
# 跳过二进制文件、权限问题等异常情况
continue
return matched_files
def write_to_log(log_path, string, filepaths):
"""
将匹配结果写入日志文件
格式:[时间戳] 搜索字符串 -> 匹配文件路径
"""
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open(log_path, 'a', encoding='utf-8') as logfile:
for path in filepaths:
log_entry = f"[{timestamp}] String '{string}' found in: {path}\n"
logfile.write(log_entry)
def main():
# 配置参数解析
parser = argparse.ArgumentParser(description='文件内容搜索程序')
parser.add_argument('--csv-dir', required=True, help='CSV文件所在目录路径')
parser.add_argument('--search-dir', required=True, help='要搜索的目录路径')
parser.add_argument('--log-file', default='search_results.log', help='日志文件路径')
args = parser.parse_args()
# 参数校验
if not os.path.isdir(args.csv_dir):
raise ValueError("CSV目录路径无效")
if not os.path.isdir(args.search_dir):
raise ValueError("搜索目录路径无效")
# 执行主流程
search_strings = read_csv_first_columns(args.csv_dir)
print(f"找到 {len(search_strings)} 个待搜索字符串")
for s in search_strings:
matched = search_string_in_files(args.search_dir, s)
if matched:
print(f"字符串 '{s}' 找到 {len(matched)} 个匹配文件")
write_to_log(args.log_file, s, matched)
if __name__ == "__main__":
main()
你感到危机了吗?