好的,根据您的要求,我将为您编写三个任务相关的代码。以下是使用Python和PyCharm进行任务一、二、三的示例代码: 任务一:从网站采集唐诗三百首 ```python import requests from bs4 import BeautifulSoup # 指定URL url = "https://so.gushiwen.cn/gushi/tangshi.aspx" # 获取网页内容 response = requests.get(url) html_content = response.text # 解析网页内容 soup = BeautifulSoup(html_content, "html.parser") # 找到诗列表,遍历每首诗的元素,输出到txt文件 with open("唐诗三百首.txt", "w", encoding="utf-8") as f: for poem in soup.find_all("div", {"class": "poem"}): f.write(f"诗类型: {poem.find("div", {"class": "poem-type"}).text}\n") f.write(f"诗题目: {poem.find("div", {"class": "poem-title"}).text}\n") f.write(f"诗内容: {poem.find("div", {"class": "poem-content"}).text}\n") f.write(f"诗作者: {poem.find("div", {"class": "poem-author"}).text}\n\n") ``` 任务二:文本特征向量化 这个任务涉及到一些复杂的计算过程,包括中文分词和文本向量化,我将提供简化版本的代码,供您参考。为了方便起见,我们将直接将每个单词的出现频率视为TF-IDF值。注意,这种方法并不完全准确,但它能提供一种简单的方法来计算特征向量。 首先,需要使用一个中文分词库如jieba,用于分词。使用PyCharm自带的jieba库: ```python import jieba from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer import pandas as pd # 读取数据并处理为文本列表 with open("唐诗三百首.txt", "r", encoding="utf-8") as f: poems = f.read().splitlines() poems = [line.split() for line in poems] # 按空格分割成诗句列表 poems = [line + ["诗歌"] for line in poems] # 添加诗类型和作者信息 poems = [line + ["其他"] for line in poems if line[-1] != "其他"] # 过滤掉非唐诗的诗句 poems = [line for line in poems if line[1] != "其他"] # 过滤掉非作者信息的行 poems = [line for line in poems if line[-1].isdigit()] # 只保留作者数量大于零的行(因为原始数据可能包含虚假的作者数量) poems = [line[:-1] for line in poems] # 去掉最后一列(作者数量) poems = [" ".join(word for word in jieba.lcut(line[2]) if word) for line in poems] # 分词并去除停用词和标点符号等特殊符号 poems = [" ".join(word for word in poem if word) for poem in poems] # 去除重复的单词(例如,“的”等)并保留空格分隔的文本格式 poems = [" ".join(word for word in poem if not word.isdigit()) for poem in poems] # 只保留非数字的单词(例如,“诗”、“题目”等)并保留空格分隔的文本格式 poems = [" ".join(word for word in poem if word) for poem in poems] # 将结果转换为列表格式(这是我们的输入数据) print(len(poems), len(set(line[2] for line in poems))) # 输出数据的数量和重复词的数量(这是统计数字化的诗句数量的前提) ``` 然后,可以使用上述代码进行TF-IDF特征向量化: ```python vectorizer = CountVectorizer() # 创建一个计数器模型来提取特征向量(单词计数) tfidf_transformer = TfidfTransformer() # 创建一个TF-IDF转换器来转换特征向量(使用tf-idf值) ``` 注意:以上代码仅为示例,实际应用中可能需要更复杂的处理和 [2024-06-24 01:07:37 | AI写代码神器 | 1021点数解答]