大数据分析与可视化 之 实验08 Pandas字符串和文本处理

发布时间 2023-12-30 20:10:03作者: Ivan丶c

实验08 Pandas字符串和文本处理

实验学时:2学时
实验类型:验证
实验要求:必修

一、实验目的

  1. 学会正确使用常见的字符串函数
    如:len()、find()、strip()、replace()、contains()函数。
  2. 解决实际数据中的字符串和文本处理问题。

二、实验要求

使用常见的字符串函数(如:len()、find()、strip()、replace()、contains()函数)等知识在PyCharm中编写程序,解决实际数据中的字符串和文本处理问题。

三、实验内容

任务1.现有一个未经清洗的数据文件lagou.csv,需要做如下数据清洗:
(1)删除多余的数据列,如公司名称、招聘职位、详细地址、职位诱惑、公司领域、公司规模;
(2)将薪资xk-xxk替换成中间值(如2K-4K替换成3K);
(3)对“职位描述”进行清洗;
(4)把“经验要求”进行清洗;(如图)
(5)保存在“lagou_clean.csv”文件中。用Python编写程序实现。
image

图1 清洗后的数据

任务2. 有一乱序的文本文件(文本文件自行定义),任意输入一个关键字,找出该关键字出现的位置,用红色字体标出,并统计出现的次数。

test8.py

import pandas as pd
import re
from colorama import init,Fore, Style  # 用于改变字体颜色
# 初始化colorama库
init(autoreset=True)


# 将薪资xk-xxk替换成中间值
def calculate_salary_midpoint(salary_str):
    if isinstance(salary_str, str):
        match = re.match(r'(\d+)k-(\d+)k', salary_str)
        if match:
            start_salary = int(match.group(1))
            end_salary = int(match.group(2))
            midpoint = (start_salary + end_salary) // 2
            return f'{midpoint}K'
    return salary_str


# 对“职位描述”进行清洗
def clean_job_description(description):
    if isinstance(description, str):
        cleaned_description = description.replace('\n', ' ').strip()
        return cleaned_description
    return description


# 把“经验要求”进行清洗
def clean_experience_requirement(experience):
    if isinstance(experience, str):
        cleaned_experience = experience.replace('经验', '').strip()
        return cleaned_experience
    return experience


def task1():
    # 读取CSV文件
    file_path = 'lagou.csv'
    df = pd.read_csv(file_path, encoding='utf-8', delimiter='|')

    # 删除多余的数据列
    columns_to_drop = ['公司名称', '招聘职位', '详细地址', '职位诱惑', '公司领域', '公司规模']
    df = df.drop(columns=columns_to_drop, errors='ignore')

    df['薪资'] = df['薪资'].apply(calculate_salary_midpoint)
    df['职位描述'] = df['职位描述'].apply(clean_job_description)
    df['经验要求'] = df['经验要求'].apply(clean_experience_requirement)

    # 保存清洗后的数据到新的CSV文件
    output_file = 'lagou_clean.csv'
    df.to_csv(output_file, index=False, encoding='utf-8-sig')

    print(f"清洗后的数据已保存到 {output_file}")


def task2():

    def highlight_keyword(text, keyword):
        # 在文本中查找关键字的出现位置
        matches = [(m.start(), m.end()) for m in re.finditer(keyword, text, re.IGNORECASE)]
        # 统计关键字出现的次数
        occurrences = len(matches)
        # 如果没有匹配到关键字,直接返回原文本
        if occurrences == 0:
            return text, occurrences
        # 对文本进行标记
        highlighted_text = ""
        start_index = 0
        for start, end in matches:
            # 添加未匹配部分
            highlighted_text += text[start_index:start]
            # 添加带颜色的关键字
            highlighted_text += Fore.RED + text[start:end] + Fore.RESET
            start_index = end
        # 添加最后一部分未匹配的文本
        highlighted_text += text[start_index:]
        return highlighted_text, occurrences

    # 读取文本文件
    with open("luanxu.txt", "r", encoding="utf-8") as file:
        content = file.read()
    # 输入关键字
    keyword_input = input("请输入关键字: ")
    # 查找并高亮关键字
    highlighted_content, occurrences_count = highlight_keyword(content, keyword_input)
    # 输出全文并用红色字体标出关键字
    print(highlighted_content)
    # 输出关键字出现的次数
    print(f"\n关键字 '{keyword_input}' 出现的次数: {occurrences_count}")


if __name__ == '__main__':
    task1()
    task2()