python 练手

本文介绍如何使用Python编写简洁代码来读取和解析日志文件,提取用户行为数据,实现在线小功能的快速执行。

周末无聊拿起很久之前买的那本 python核心编程,翻了一下,感觉python果然简洁,比java方便多了。如果线上需要执行一个业务简单的小功能,完全可以直接写个python文件扔到线上直接执行。

下面是读取log日志的,先记录,继续改进中

# -*- coding: UTF-8 –*-
'''
Created on 2012-5-26

@author: lyh
'''
def loadfile():
    myfile = open("C:\Users\lyh\Desktop\log", "r")
    dict = {}
    for line in myfile:
        viewIndex = line.find("正在查看资讯")
        if(viewIndex > 0):
            userIndex = line.find("用户:")
            if (userIndex > 0):
                nameIndex = line.find(",IP")
                username = line[userIndex + 9:nameIndex]
                try:
                    if(username != "null"):
                        viewId = line[viewIndex + 21:]
                        if (username in dict):
                            dict[username] = dict[username] + "," + viewId
                        else:
                            dict[username] = viewId
                except Exception,e: 
                    print e
    myfile.close();  
                  
    for i in dict.keys():
        print 'key=%s,value=%s' % (i, dict[i])
                
            
if __name__ == '__main__':
    loadfile()
    pass
 
适合练手Python项目有很多,以下为你介绍几种不同类型的项目: - **基础脚本类**: - **文件批量重命名**:可以编写一个Python脚本,对指定文件夹下的所有文件进行批量重命名操作。例如,将所有图片文件的文件名前加上特定前缀。 ```python import os folder_path = 'your_folder_path' prefix = 'new_' for filename in os.listdir(folder_path): if filename.endswith(('.jpg', '.png')): new_filename = prefix + filename os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename)) ``` - **简单的计算器**:实现一个能进行加、减、乘、除运算的命令行计算器。 ```python def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y != 0: return x / y else: return "Error: division by zero" num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == '+': print(add(num1, num2)) elif operation == '-': print(subtract(num1, num2)) elif operation == '*': print(multiply(num1, num2)) elif operation == '/': print(divide(num1, num2)) else: print("Invalid operation") ``` - **Web开发类**: - **简单的Flask博客**:使用Flask框架搭建一个简单的博客系统,实现文章的发布、查看功能。 ```python from flask import Flask, render_template, request app = Flask(__name__) posts = [] @app.route('/') def index(): return render_template('index.html', posts=posts) @app.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'POST': title = request.form.get('title') content = request.form.get('content') posts.append({'title': title, 'content': content}) return "Post added successfully" return render_template('add.html') if __name__ == '__main__': app.run(debug=True) ``` - **数据处理类**: - **CSV文件数据处理**:读取一个包含学生成绩的CSV文件,计算每个学生的平均分,并将结果保存到新的CSV文件中。 ```python import csv with open('grades.csv', 'r') as file: reader = csv.reader(file) header = next(reader) students = [] for row in reader: name = row[0] grades = [float(grade) for grade in row[1:]] average = sum(grades) / len(grades) students.append([name, average]) with open('average_grades.csv', 'w', newline='') as new_file: writer = csv.writer(new_file) writer.writerow(['Name', 'Average Grade']) writer.writerows(students) ``` - **爬虫类**: - **爬取豆瓣电影Top250信息**:使用`requests`和`BeautifulSoup`库爬取豆瓣电影Top250的电影名称、评分等信息。 ```python import requests from bs4 import BeautifulSoup url = 'https://movie.douban.com/top250' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') items = soup.find_all('div', class_='item') for item in items: title = item.find('span', class_='title').text rating = item.find('span', class_='rating_num').text print(f'Title: {title}, Rating: {rating}') ``` 另外,还可参考一些项目资源,如《Python项目开发实战1 - 50 高清完整.pdf版》(下载地址:https://gitcode.com/Open-source-documentation-tutorial/dcbb2 ),有50个精选项目案例,全面覆盖Python在实际应用中的核心技术和编程技巧;70个Python练手项目列表(都有完整教程),可在http://www.jianshu.com/p/b577a1655144 查看,但需要注册实验楼账号 [^1][^2]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值