牛客网--关于替换空格

牛客网--关于替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

代码

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int countSpace = 0;
        for(int i = 0; i < str.length(); i++)
        {
            char c = str.charAt(i);
            if(c == ' ')
            {
                countSpace++;
            }
        }
        int oldIndex = str.length() - 1;
        int newIndex = oldIndex + 2 * countSpace;
        str.setLength(newIndex + 1);
        while(oldIndex < newIndex && oldIndex >= 0)
        {
            char c = str.charAt(oldIndex);
            if(c == ' ')
            {
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
            }
            else
            {
                str.setCharAt(newIndex--, c);
            }
            oldIndex--;
        }
        return str.toString();
    }
}
要完成你的需求——从牛客网“剑指Offer”题库中获取表格中的全部题目,并保存到本地桌面“简历”文件夹中,我们需要分几个步骤来实现: --- ### ✅ 需求分析 1. **目标网页**:[https://www.nowcoder.com/ta/coding-interviews](https://www.nowcoder.com/ta/coding-interviews) 2. **目标数据**:表格中的题目名称、难度、通过率、链接等信息。 3. **输出方式**:将数据保存为 `.csv` 或 `.xlsx` 文件,存储在 `桌面/简历/` 文件夹中。 4. **技术手段**:使用 Python 的 `requests` + `BeautifulSoup` 爬取网页内容(注意:牛客网不反爬较弱,但需遵守 robots.txt 和合理频率)。 ⚠️ 注意: - 牛客网部分页面是动态加载的(JavaScript 渲染),该页面的题目列表是服务端渲染的,可以直接抓取 HTML。 - 本操作仅用于个人学习用途,请勿用于商业传播或大规模爬取。 --- ### ✅ 完整代码实现 ```python import os import csv import requests from bs4 import BeautifulSoup from urllib.parse import urljoin # 目标URL URL = "https://www.nowcoder.com/ta/coding-interviews" # 设置请求头,模拟浏览器访问 HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } def get_questions(): # 发送请求 response = requests.get(URL, headers=HEADERS) if response.status_code != 200: raise Exception(f"Failed to access page, status code: {response.status_code}") # 解析HTML soup = BeautifulSoup(response.text, 'html.parser') # 查找题目表格(根据实际HTML结构调整) table = soup.find('table', class_='nk-table') if not table: raise Exception("Cannot find the question table on the page.") questions = [] rows = table.find('tbody').find_all('tr') for row in rows: cols = row.find_all('td') if len(cols) < 4: continue title_tag = cols[1].find('a') title = title_tag.get_text(strip=True) # 题目名称 link = urljoin(URL, title_tag['href']) # 完整链接 difficulty = cols[2].get_text(strip=True) # 难度 pass_rate = cols[3].get_text(strip=True) # 通过率 questions.append({ 'title': title, 'difficulty': difficulty, 'pass_rate': pass_rate, 'url': link }) return questions def save_to_csv(questions, folder_path, filename="jianzhi_offer_questions.csv"): filepath = os.path.join(folder_path, filename) with open(filepath, mode='w', encoding='utf-8', newline='', errors='ignore') as f: writer = csv.DictWriter(f, fieldnames=['title', 'difficulty', 'pass_rate', 'url']) writer.writeheader() writer.writerows(questions) print(f"✅ 数据已保存至: {filepath}") def main(): # 构建桌面“简历”路径 desktop = os.path.join(os.path.expanduser("~"), "Desktop") resume_folder = os.path.join(desktop, "简历") # 创建文件夹(如果不存在) os.makedirs(resume_folder, exist_ok=True) try: print("🚀 正在爬取剑指Offer题目...") questions = get_questions() print(f"📖 共获取 {len(questions)} 道题目。") save_to_csv(questions, resume_folder) except Exception as e: print(f"❌ 出错: {e}") if __name__ == "__main__": main() ``` --- ### 🔍 代码解释 | 模块 | 功能说明 | |------|---------| | `requests` | 向目标网页发起 HTTP 请求 | | `BeautifulSoup` | 解析 HTML 页面,提取表格数据 | | `os` / `csv` | 创建文件夹、写入 CSV 文件 | | `urljoin` | 将相对链接转为绝对链接 | > ✅ 提取逻辑基于当前牛客网 HTML 结构(`.nk-table` 是其常用类名)。若未来页面改版,可能需要更新选择器。 --- ### 📂 输出结果 运行后将在你的电脑桌面上创建或使用已有 `简历` 文件夹,并生成一个名为 `jianzhi_offer_questions.csv` 的文件,内容如下: ``` title,difficulty,pass_rate,url 二维数组中的查找,简单,80%,https://www.nowcoder.com/... 替换空格,简单,70%,https://www.nowcoder.com/... ... ``` 你可以用 Excel 打开查看。 --- ### ⚠️ 注意事项 1. **网络环境**:确保可以访问牛客网。 2. **反爬策略**:不要频繁请求,建议只运行一次。 3. **依赖安装**:运行前请安装所需库: ```bash pip install requests beautifulsoup4 ``` 4. **编码问题**:CSV 使用 UTF-8 编码,中文不会乱码。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值