在本文中,我将解释如何使用潜在语义分析(LSA)从一组新闻文章中聚类和查找类似的新闻文档。
LSA是一种NLP技术,用于找出一组文档中隐藏的概念或主题。
数据读取
首先导入一些必要的Python库:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport sysimport nltk# nltk.download('stopwords')from nltk.corpus import stopwords# from bs4 import BeautifulSoup as Soupimport json
我的机器学习样本数据:
以下Python代码用于在字符串列表中加载和存储数据,这部分完全取决于数据类型:
def parseLog(file): file = sys.argv[1] content = [] with open(file) as f: content = f.readlines() content = [json.loads(x.strip()) for x in content] # print(content) data = json.loads(json.dumps(content)) k=0# preprocessing content_list = [] for i in data: string_content = "" if "contents" in i: for all in i["contents"]: if "content" in all: # print(str(all["content"])) string_content = string_content + str(all["content"]) content_list.append(string_content)
content_list包含字符串列表中的完整数据。因此,如果有45000篇文章,content_list有45000个字符串。
数据预处理
现在我们将使用pandas来应用一些机器学习中的预处理技术。首先,我们将尝试尽可能地清理文本数据。想法是使用regex replace(" [^a-zA-Z#] ", " ")一次性删除标点、数字和特殊字符,它将替换除空格以外的所有字符。然后我们将删除较短的单词,因为它们通常不包含有用的信息。最后,我们将所有文本都小写。
news_df = pd.DataFrame({'document':content_list}) # removing everything except alphabets` news_df['clean_doc'] = news_df['document'].str.replace("[^a-zA-Z#]