Website

编程资源导航
[b]Java:[/b]
[url]http://docs.oracle.com/javase/[/url]
[url]http://docs.oracle.com/javase/7/docs/index.html[/url]
[url]https://tomcat.apache.org/tomcat-7.0-doc/index.html[/url]
[url]http://docs.oracle.com/javaee/[/url]
[url]http://docs.oracle.com/javaee/6/api/[/url]

OpenJDK官网:[url]http://openjdk.java.net/[/url]
代码库:[url]http://hg.openjdk.java.net/[/url]

JDK7 update的代码仓库森林(repo forest),下面有hotspot、jdk等目录:
[url]http://hg.openjdk.java.net/jdk7u/jdk7u[/url]
Hotspot:
[url]http://hg.openjdk.java.net/jdk7u/jdk7u/hotspot[/url]
JDK:
[url]http://hg.openjdk.java.net/jdk7u/jdk7u/jdk[/url]
API:平台无关的Java代码实现
[url]http://hg.openjdk.java.net/jdk7u/jdk7u/jdk/file/tip/src/share/classes/[/url]
OpenJDK在线源码:
[url]http://www.docjar.com/projects/openjdk-7-code.html[/url]

阅读openjdk源代码:[url]http://hllvm.group.iteye.com/group/topic/35385[/url]

==================================================================================

[b]Oracle:[/b]
[url]http://www.oracle.com/pls/db112/homepage[/url]
[url]http://www.oracle.com/pls/db102/homepage[/url]

[url]http://asktom.oracle.com[/url]

[url]http://tahiti.oracle.com/[/url]
[url]http://docs.oracle.com/[/url]

[url]http://www.ixora.com.au/[/url]
[url]http://www.dba-oracle.com/[/url]

==================================================================================

[b]Javascript:[/b]
[url]https://developer.mozilla.org/en-US/[/url]
[url]https://developer.mozilla.org/zh-CN/[/url]

[url]http://www.w3schools.com/[/url]
[url]http://www.w3school.com.cn/[/url]
[url]http://www.w3help.org/zh-cn/standards/[/url]
[url]http://www.chinaw3c.org/[/url]
[url]http://www.w3.org/[/url]
[url]http://www.ecma-international.org/default.htm[/url]

JS牛人们:
JS之父:[url]http://brendaneich.com/[/url]
JS大宗师(Yoda):[url]http://crockford.com/[/url]
JQuery之父:[url]http://ejohn.org/[/url]
[url]http://dean.edwards.name/[/url]
[url]http://www.paulirish.com/[/url]
[url]http://alexsexton.com/[/url]
[url]http://remysharp.com/[/url]
[url]http://mir.aculo.us/[/url]
[url]http://www.nczonline.net/[/url]
[url]http://www.phpied.com/[/url]

JavaScript 标准教程(阮一峰)[url]http://javascript.ruanyifeng.com/[/url]
[url]http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html[/url]
ECMA-262:[url]http://dmitrysoshnikov.com/[/url]
[url]http://wenku.baidu.com/view/ffe75b661ed9ad51f01df2d7.html[/url]

[url]http://dmitrysoshnikov.com/[/url]

==================================================================================
[b]Golang[/b]
[url]http://golang.org/[/url]
A Tour of Go:[url]http://tour.golang.org/[/url]
[url]http://code.google.com/p/go/[/url]
[url]http://code.google.com/p/golangide/[/url]
[url]http://www.bigendian123.com/[/url]


==================================================================================
[url]RFC:[/url]
[url]http://www.ietf.org/[/url]
[url]http://www.rfc-editor.org/[/url]

[url]http://www.rfc-editor.org/rfcxx00.html[/url]
[url]http://www.ietf.org/rfc/rfc-index[/url]

[url]http://www.rfc-editor.org/rfc/[/url]
[url]http://www.ietf.org/rfc/[/url]

[url]http://datatracker.ietf.org/[/url]

[url]http://www.cnpaf.net/class/rfcall/[/url]
[url]http://www.cnpaf.net/class/rfc/[/url]


==================================================================================
[b]Perl:[/b]
[url]http://www.perl.org/[/url]

[url]http://perldoc.perl.org/[/url]

[url]http://www.perl6.org/[/url]
# -*- coding: utf-8 -*- """ 网站爬取脚本(优化版): - 读取 data_cn_en.csv(URL列表) - 爬取网站文本并清理 - 每爬取1条记录实时追加保存到CSV - 遇到错误网站直接跳过,不中断整体流程 """ import pandas as pd import requests from bs4 import BeautifulSoup, element import spacy as sp from spacy.language import Language import jieba import os from tqdm import tqdm import traceback from urllib.parse import urlparse # 提前导入URL解析模块 # 打印当前模块导入情况,帮助排查命名冲突 print("=" * 50) print("当前导入模块检查:") print(f"pandas: {pd.__name__} v{pd.__version__}") print(f"requests: {requests.__name__}") print(f"BeautifulSoup: {BeautifulSoup.__name__}") print(f"spacy: {sp.__name__} v{sp.__version__}") print(f"jieba: {jieba.__name__}") print(f"tqdm: {tqdm.__name__}") print("=" * 50) # -------------------------- 1. 初始化文本处理工具 -------------------------- print("\n[初始化] 开始初始化文本处理工具...") try: print("[初始化] 尝试加载spaCy英文模型...") nlp = sp.load("en_core_web_sm") print("[初始化] spaCy模型加载成功") except Exception as e: print(f"[初始化错误] spaCy模型加载失败: {str(e)}") print("请先安装spaCy英文模型:python -m spacy download en_core_web_sm") exit(1) @Language.component("jieba_tokenizer") def jieba_tokenizer(doc): """中文文本分词组件(spaCy管道)""" try: text = doc.text has_chinese = any('\u4e00' <= char <= '\u9fff' for char in text) if has_chinese: words = jieba.lcut(text) spaces = [False] * len(words) return sp.tokens.Doc(doc.vocab, words=words, spaces=spaces) else: return doc except Exception as e: print(f"[分词错误] jieba_tokenizer出错: {str(e)}") traceback.print_exc() return doc try: nlp.add_pipe("jieba_tokenizer", before="parser") print("[初始化] jieba分词管道添加成功") except Exception as e: print(f"[初始化错误] 添加jieba分词管道失败: {str(e)}") traceback.print_exc() exit(1) # -------------------------- 2. 网站爬取工具 -------------------------- class ScrapTool: def visit_url(self, website_url): """ 爬取单个URL的核心方法 返回:包含URL、网站名、原始文本的字典(失败时文本为空) """ try: print(f"\n[爬取] 处理URL: {website_url}") # 补全URL前缀(若缺失http/https) if not website_url.startswith(("http://", "https://")): website_url = f"https://{website_url}" print(f"[爬取] 补全URL为: {website_url}") # 模拟浏览器请求头(降低反爬概率) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1' } # 发送请求(超时30秒,避免卡死) print(f"[爬取] 发送请求到: {website_url}") response = requests.get(website_url, headers=headers, timeout=30) response.raise_for_status() # 触发HTTP错误(如404、500) # 解析网页内容 print(f"[爬取] 成功获取响应,状态码: {response.status_code}") soup = BeautifulSoup(response.content, "lxml") # 整合网页关键文本(标题+Meta+标题标签+正文) print("[爬取] 提取网页内容...") website_text = ( self.get_html_title_tag(soup) + " " + self.get_html_meta_tags(soup) + " " + self.get_html_heading_tags(soup) + " " + self.get_text_content(soup) ).strip() # 返回成功结果 result = { "website_url": website_url, "website_name": self.get_website_name(website_url), "website_text": website_text } print(f"[爬取] 成功处理URL: {website_url}(文本长度:{len(website_text)}字符)") return result except Exception as e: # 捕获所有异常,返回失败结果(文本为空) error_msg = str(e)[:100] + "..." if len(str(e)) > 100 else str(e) print(f"[爬取错误] 处理 {website_url} 失败:{error_msg}") traceback.print_exc() # 打印详细错误堆栈(便于调试) return { "website_url": website_url, "website_name": self.get_website_name(website_url) if website_url else "", "website_text": "" # 错误时文本为空 } def get_website_name(self, website_url): """从URL中提取网站名(如:www.baidu.com → baidu)""" try: parsed = urlparse(website_url) netloc = parsed.netloc # 获取域名(如:www.baidu.com) name_parts = netloc.split(".") # 处理二级/三级域名(如:blog.youkuaiyun.com → csdn,www.taobao.com → taobao) return name_parts[-2] if len(name_parts) >= 2 else netloc except Exception as e: print(f"[提取网站名错误] {str(e)}") return "" def get_html_title_tag(self, soup): """提取网页<title>标签内容""" try: if soup.title and soup.title.contents: title = '. '.join([str(c).strip() for c in soup.title.contents]) return title[:200] # 限制长度,避免异常长标题 return "" except Exception as e: print(f"[提取标题错误] {str(e)}") return "" def get_html_meta_tags(self, soup): """提取网页Meta标签(keywords/description)""" try: meta_tags = soup.find_all( lambda tag: tag.name == "meta" and tag.has_attr('name') and tag.has_attr('content') ) meta_content = [str(tag["content"]).strip() for tag in meta_tags if tag["name"].lower() in ['keywords', 'description']] return ' '.join(meta_content)[:500] # 限制长度 except Exception as e: print(f"[提取Meta错误] {str(e)}") return "" def get_html_heading_tags(self, soup): """提取网页H1-H6标题标签""" try: heading_tags = soup.find_all(["h1", "h2", "h3", "h4", "h5", "h6"]) heading_content = [" ".join(tag.stripped_strings) for tag in heading_tags] return ' '.join(heading_content)[:300] # 限制长度 except Exception as e: print(f"[提取标题标签错误] {str(e)}") return "" def get_text_content(self, soup): """提取网页正文文本(过滤无用标签)""" try: # 忽略的无用标签(避免爬取样式、脚本等内容) ignore_tags = ['style', 'script', 'head', 'title', 'meta', '[document]', "noscript", "iframe", "nav", "footer", "aside"] text_tags = soup.find_all(string=True) valid_text = [] for tag in text_tags: stripped_text = tag.strip() # 过滤条件:非忽略标签、非注释、非纯数字、非空文本 if (tag.parent.name not in ignore_tags and not isinstance(tag, element.Comment) and not stripped_text.isnumeric() and len(stripped_text) > 1): # 过滤单个字符(如标点、空格) valid_text.append(stripped_text) return ' '.join(valid_text)[:2000] # 限制长度,避免异常长文本 except Exception as e: print(f"[提取正文错误] {str(e)}") return "" # -------------------------- 3. 文本清理函数 -------------------------- def clean_text(raw_text): """ 清理原始网页文本: 1. 过滤停用词、标点、纯数字 2. 英文词形还原(如:running → run) 3. 统一小写 """ try: if not raw_text or raw_text.strip() == "": return "" # 空文本直接返回 # 使用spaCy处理文本 doc = nlp(raw_text) tokens = [] exclusion_list = ["nan", "none", "null"] # 额外排除的无效文本 for token in doc: # 过滤条件:非停用词、非标点、非纯数字、非特殊字符、不在排除列表 if (not token.is_stop and not token.is_punct and not token.text.isnumeric() and (token.text.isalnum() or '\u4e00' <= token.text <= '\u9fff') and token.text.lower() not in exclusion_list): # 中文直接取文本,英文取词形还原 cleaned_token = token.text.lower().strip() if '\u4e00' <= token.text <= '\u9fff' else str( token.lemma_).lower().strip() tokens.append(cleaned_token) return " ".join(tokens) # 拼接清理后的词 except Exception as e: print(f"[文本清理错误] {str(e)}") traceback.print_exc() return "" # -------------------------- 4. 核心爬取流程(实时保存+错误跳过) -------------------------- def main(): # 配置文件路径 input_csv_path = "data_cn_en.csv" output_csv_path = "data_with_cleaned_text.csv" # 检查输入文件是否存在 if not os.path.exists(input_csv_path): print(f"[错误] 输入文件 {input_csv_path} 不存在!") exit(1) # 读取原始CSV(假设格式:id, url, category) print("\n[主流程] 读取原始数据集...") try: df = pd.read_csv( input_csv_path, header=None, names=["id", "url", "category"], encoding="utf-8" ) print(f"[主流程] 读取完成,共 {len(df)} 条URL记录") except Exception as e: print(f"[读取CSV错误] {str(e)}") exit(1) # 初始化爬虫工具 scrap_tool = ScrapTool() print("[主流程] 爬虫工具初始化完成,开始爬取...") # 初始化进度条 pbar = tqdm(total=len(df), desc="整体爬取进度") # 遍历每条URL(逐个处理+实时保存) for idx, row in df.iterrows(): try: # 获取当前行数据 record_id = row["id"] url = row["url"] category = row["category"] print(f"\n[主流程] 处理第 {idx + 1}/{len(df)} 条记录(ID:{record_id})") # 1. 爬取URL内容 crawl_result = scrap_tool.visit_url(url) # 2. 清理文本 cleaned_text = clean_text(crawl_result["website_text"]) print(f"[主流程] 文本清理完成(清理后长度:{len(cleaned_text)}字符)") # 3. 构造最终记录 final_record = pd.DataFrame({ "id": [record_id], "url": [url], # 保留原始URL(未补全前) "website_name": [crawl_result["website_name"]], "website_text": [crawl_result["website_text"]], "cleaned_website_text": [cleaned_text], "category": [category], "status": ["成功" if cleaned_text else "失败"] # 标记爬取状态 }) # 4. 实时追加保存到CSV(不存在则创建,存在则追加) if not os.path.exists(output_csv_path): # 首次保存:写入表头 final_record.to_csv(output_csv_path, index=False, encoding="utf-8", mode="w") else: # 后续保存:追加(不写表头) final_record.to_csv(output_csv_path, index=False, encoding="utf-8", mode="a", header=False) print(f"[主流程] 第 {idx + 1} 条记录已保存到 {output_csv_path}") except Exception as e: # 捕获单条记录的所有异常,直接跳过(不中断循环) print(f"[主流程警告] 第 {idx + 1} 条记录处理失败,已跳过:{str(e)}") traceback.print_exc() # 更新进度条 pbar.update(1) # 爬取完成,打印统计信息 pbar.close() print("\n" + "=" * 50) print("[主流程] 所有URL处理完成!") # 读取输出文件,统计成功/失败数 if os.path.exists(output_csv_path): output_df = pd.read_csv(output_csv_path, encoding="utf-8") total = len(output_df) success = len(output_df[output_df["cleaned_website_text"] != ""]) fail = total - success print(f"\n[统计信息]") print(f" - 总处理数:{total}") print(f" - 成功数(有效文本):{success}") print(f" - 失败数(无有效文本):{fail}") print(f" - 成功率:{success / total * 100:.1f}%" if total > 0 else " - 成功率:0%") print(f"\n输出文件路径:{os.path.abspath(output_csv_path)}") else: print(f"[警告] 未生成输出文件 {output_csv_path}(可能所有记录处理失败)") if __name__ == "__main__": try: print("=" * 50) print("程序开始执行(优化版:实时保存+错误跳过)") print("=" * 50) # 检查必要依赖(提前捕获缺失依赖) required_libs = ["pandas", "requests", "bs4", "spacy", "jieba", "tqdm"] for lib in required_libs: __import__(lib) print("[依赖检查] 所有必要依赖均已安装") # 执行主流程 main() except ImportError as e: # 处理缺失依赖的错误 missing_lib = str(e).split("'")[1] print(f"\n[依赖错误] 缺少必要库:{missing_lib}") print("请执行以下命令安装所有依赖:") print("pip install pandas requests beautifulsoup4 spacy jieba tqdm") if "spacy" in missing_lib or "en_core_web_sm" in str(e): print("并安装spaCy英文模型:python -m spacy download en_core_web_sm") except Exception as e: # 处理程序启动时的致命错误 print(f"\n[程序致命错误] 启动失败:{str(e)}") traceback.print_exc() 这段代码清理爬取的文本时忘记给中文设置停用词了,请写一个程序重新处理一下data_with_cleaned_text.csv文件中的cleaned_website_text
09-05
<think> 我们注意到原程序在清理文本时,只使用了spaCy的英文停用词,而没有为中文设置停用词。因此,我们需要重新处理已经生成的CSV文件,对`cleaned_website_text`列进行中文停用词的过滤。 步骤: 1. 读取`data_with_cleaned_text.csv`文件。 2. 为中文停用词做准备:我们可以使用jieba的内置停用词列表,或者使用第三方停用词表(这里使用jieba自带的停用词表,并补充一些常见的停用词)。 3. 定义一个函数,专门用于中文文本的停用词过滤(注意:原始清理函数中已经处理了英文,这里我们主要针对中文部分进行二次过滤)。 4. 遍历每一行,对`cleaned_website_text`进行中文停用词过滤(注意:该列可能包含中英文混合的文本,但之前已经分过词,所以我们按空格分割后过滤)。 5. 注意:原清理函数已经将文本转换为小写,所以停用词表也需要使用小写。 6. 将处理后的结果保存回同一个CSV文件(覆盖原列)或者另存为新文件(这里我们选择覆盖原列并保存到新文件,以防万一)。 考虑:由于原程序可能已经进行了一些处理,我们重新处理时应该只针对中文停用词进行补充过滤。原清理函数已经做了以下事情: - 过滤了停用词(英文)、标点、数字等。 - 英文词形还原。 - 统一小写。 现在的问题是中文停用词没有过滤,所以我们需要在已经分好的词(用空格分隔)中,去掉中文停用词。 具体步骤: 1. 加载中文停用词表(可以使用`jieba.analyse`中的停用词表,或者从文件加载。这里我们直接使用`jieba`自带的停用词表路径,但需要注意`jieba`可能没有默认下载停用词表,所以我们可以使用一个内置的停用词列表作为备选)。 2. 定义一个函数`filter_chinese_stopwords(text)`,接收一个字符串(由空格分隔的单词组成),然后移除其中的中文停用词。 3. 注意:文本中可能同时包含中英文,我们只需要移除中文停用词,英文停用词已经在之前被移除过了(但可能有遗漏?)。为了保险,我们也可以同时过滤英文停用词(但原程序已经过滤了一次,这里我们主要是补充中文停用词过滤,所以可以只过滤中文停用词)。 4. 处理后的文本重新用空格拼接。 但是,由于原清理函数已经进行了分词(中英文分开处理),我们重新处理时只需要按空格分割,然后过滤停用词。 另外,我们注意到原清理函数对中文的处理是直接使用jieba分词,然后每个词作为一个token(没有去掉停用词)。所以我们需要在重新处理时去掉这些停用词。 实现: 1. 使用jieba自带的停用词表:`stop_words = set(line.strip() for line in open('stop_words.txt', encoding='utf-8'))`,但是我们需要一个确切的停用词表路径。我们可以使用jieba默认的停用词表(如果有的话),或者使用一个通用的停用词表。 由于我们不知道jieba的停用词表具体在哪里,我们可以使用以下方法获取: - 从网上下载一个常用的中文停用词表(如百度停用词表、哈工大停用词表等) - 或者使用一个内置的停用词列表(这里为了简单,我们使用一个内置的列表,但考虑到通用性,我们使用jieba源码中提供的停用词表路径,不过需要先确定是否存在) 实际上,jieba没有自带停用词表文件,但通常我们会自己准备一个。因此,我们可以从网上下载一个,或者使用一个已有的停用词集合。 这里,我们使用一个折中的办法:使用`jieba.analyse`中的`STOP_WORDS`(如果可用)。但注意,这个停用词表可能不是完整的。 另外,我们可以直接使用一个在线的停用词表(比如在代码中内置一个常见的停用词列表)。但为了灵活性,我建议使用外部文件,并放在同一目录下(文件名:`chinese_stopwords.txt`)。如果文件不存在,则使用一个内置的停用词列表(从网络资源中获取的一些常见停用词)。 但是,题目中没有提供停用词表,所以我们需要自己内置一个较小的停用词列表作为备选,同时允许使用外部文件。 考虑到程序健壮性,我们这样做: - 尝试从当前目录下的`chinese_stopwords.txt`文件加载停用词。 - 如果文件不存在,则使用一个内置的停用词列表(通过一个列表定义)。 内置停用词列表我们可以参考常用的一些停用词(如:的、了、是、在、我、你、他、和、等)。 由于我们无法保证内置停用词表完整,所以最好还是提供一个外部文件。但在代码中,我们将内置一个基础的中文停用词表。 具体代码步骤: 1. 定义重新处理文本的函数,包含中文停用词过滤。 2. 读取CSV文件。 3. 对每一行的`cleaned_website_text`列应用过滤函数。 4. 将结果保存到新的列或者替换原列(这里我们替换原列,并保存为新文件,以防出错)。 5. 保存修改后的DataFrame到新的CSV文件(例如:`data_with_cleaned_text_stopwords_removed.csv`)。 注意:原始清理文本可能为空(失败记录),需要跳过处理。 代码实现: 由于我们不确定原CSV文件是否有其他列,我们只修改`cleaned_website_text`列。 我们这样设计: - 输入文件:`data_with_cleaned_text.csv` - 输出文件:`data_with_cleaned_text_stopwords_removed.csv` 步骤: 1. 加载停用词表(从文件或内置列表)。 2. 读取CSV文件。 3. 对每一行,如果`cleaned_website_text`不为空,则进行中文停用词过滤。 4. 将过滤后的文本替换原来的文本。 5. 保存。 停用词过滤函数: ```python def remove_stopwords(text, stopwords): if not text or text.strip() == "": return text words = text.split() # 过滤停用词 filtered_words = [word for word in words if word not in stopwords] return " ".join(filtered_words) ``` 停用词表加载: ```python def load_stopwords(file_path="chinese_stopwords.txt"): stopwords = set() # 尝试从文件加载 if os.path.exists(file_path): try: with open(file_path, 'r', encoding='utf-8') as f: for line in f: word = line.strip() if word: stopwords.add(word) except Exception as e: print(f"加载停用词文件失败: {e}, 使用内置停用词表") stopwords = get_builtin_stopwords() else: print(f"停用词文件 {file_path} 不存在,使用内置停用词表") stopwords = get_builtin_stopwords() return stopwords def get_builtin_stopwords(): # 返回一个内置的停用词集合 builtin_stopwords = {"的", "了", "和", "是", "在", "我", "你", "他", "她", "它", "我们", "你们", "他们", "这", "那", "啊", "哦", "呢", "吧", "呀", "自己", "什么", "怎么", "为什么", "可以", "因为", "所以", "但", "而", "并且", "或", "如果", "就", "则", "只", "也", "有", "没有", "不", "要", "会", "能", "可能", "应该", "一定", "非常", "很", "更", "最", "太", "又", "再", "还", "没", "已经", "将", "已", "了", "着", "过", "啊", "哦", "嗯", "唉", "啦", "吗", "么", "为", "为了", "与", "关于", "对", "对于", "中", "上", "下", "内", "外", "之间", "之中", "之一", "等等", "等", "些", "个", "年", "月", "日", "时", "分", "秒", "点", "分钟", "小时", "天", "周", "星期", "月份", "年份", "今天", "明天", "昨天", "前天", "后天", "去年", "明年", "上个月", "下个月", "这个", "那个", "这些", "那些", "这样", "那样", "这里", "那里", "这时", "那时", "谁", "何时", "何地", "如何", "为什么", "哪个", "多少", "几", "第几", "每", "各", "每", "所有", "任何", "一些", "全部", "部分", "其他", "其余", "另外", "其实", "实际上", "特别", "尤其", "例如", "比如", "诸如", "一些", "一下", "一点", "一切", "一种", "一样", "一般", "一直", "一起", "一定", "一切", "一下", "一点", "一种", "一样", "一般", "一直", "一起", "一定", "一切", "一下", "一点", "一种", "一样", "一般", "一直", "一起", "一定", "一切", "一下", "一点", "一种", "一样", "一般", "一直", "一起", "一定", "一切", "一下", "一点", "一种", "一样", "一般", "一直", "一起", "一定", "一切", "一下", "一点"} return builtin_stopwords ``` 注意:内置停用词表可能不够全面,但可以作为一个基础。 最后,我们编写一个脚本执行上述过程。 考虑到原程序已经生成了CSV文件,我们重新处理该文件即可。 下面编写完整的代码: </think> 为了解决中文停用词缺失的问题,我将编写一个程序来重新处理 CSV 文件中的 `cleaned_website_text` 列,添加中文停用词过滤功能: ```python # -*- coding: utf-8 -*- """ 脚本功能:重新处理CSV文件,添加中文停用词过滤 输入文件:data_with_cleaned_text.csv 输出文件:data_with_cleaned_text_chinese_stopwords_removed.csv """ import pandas as pd import jieba import os # 中文停用词列表(可扩展) CHINESE_STOPWORDS = { '的', '了', '在', '是', '我', '你', '他', '她', '它', '我们', '你们', '他们', '这', '那', '啊', '哦', '呢', '吧', '呀', '吗', '啦', '和', '与', '或', '而', '并', '但', '就', '很', '非常', '太', '不', '没', '没有', '无', '非', '别', '自己', '什么', '怎么', '为什么', '可以', '因为', '所以', '虽然', '即使', '并且', '如果', '则', '只', '也', '有', '要', '会', '能', '可能', '应该', '一定', '非常', '更', '最', '太', '又', '再', '还', '没', '已经', '将', '曾经' } def remove_chinese_stopwords(text): """移除中文停用词并重新拼接文本""" if not isinstance(text, str) or text.strip() == "": return text # 使用jieba分词 words = jieba.lcut(text) # 过滤停用词 filtered_words = [word for word in words if word not in CHINESE_STOPWORDS] return " ".join(filtered_words) def main(): input_file = "data_with_cleaned_text.csv" output_file = "data_with_cleaned_text_chinese_stopwords_removed.csv" # 检查输入文件是否存在 if not os.path.exists(input_file): print(f"[错误] 输入文件 {input_file} 不存在!") exit(1) print(f"[处理] 正在读取输入文件: {input_file}") try: # 读取CSV文件 df = pd.read_csv(input_file, encoding="utf-8") total_records = len(df) print(f"[处理] 成功读取 {total_records} 条记录") # 处理文本并更新cleaned_website_text列 print("[处理] 开始移除中文停用词...") df["cleaned_website_text"] = df["cleaned_website_text"].apply(remove_chinese_stopwords) # 保存到新文件 df.to_csv(output_file, index=False, encoding="utf-8") print(f"[处理] 处理完成!结果已保存到: {output_file}") # 统计成功/失败记录 success_count = df[df["cleaned_website_text"] != ""].shape[0] print(f"\n[统计] 总记录数: {total_records}") print(f"[统计] 成功处理数: {success_count}") print(f"[统计] 空文本记录数: {total_records - success_count}") except Exception as e: print(f"[处理错误] 处理过程中发生错误: {str(e)}") exit(1) if __name__ == "__main__": print("=" * 50) print("中文停用词处理程序启动") print("=" * 50) main() ``` ### 程序说明: 1. **中文停用词列表**: - 预定义了常见中文停用词集合 `CHINESE_STOPWORDS` - 可根据需要扩展该列表 2. **处理流程**: - 读取 `data_with_cleaned_text.csv` 文件 - 对 `cleaned_website_text` 列应用停用词过滤: - 使用 jieba 进行中文分词 - 过滤停用词后重新拼接文本 - 结果保存到新文件 `data_with_cleaned_text_chinese_stopwords_removed.csv` 3. **统计信息**: - 输出处理前后的记录统计 - 区分有效文本和空文本记录 ### 使用方法: 1. 确保安装了依赖库:`pip install pandas jieba` 2. 将脚本与 `data_with_cleaned_text.csv` 放在同一目录 3. 运行脚本即可生成处理后的文件
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值