
在进行文本分析,特别是构建文档-词矩阵(document-term matrix, dtm)时,我们通常会从多个文本文件中提取词频或tf-idf值。默认情况下,pandas dataframe会为每一行分配一个从0开始的数字索引。然而,为了更好地理解数据,将每一行与它所代表的原始文件名关联起来是至关重要的。例如,当处理按年份命名的文件(如"1905.txt")时,将年份作为行索引能极大提高数据的可读性和分析效率。
假设我们已经从一系列.txt文件中读取内容,并使用sklearn.feature_extraction.text.CountVectorizer生成了一个文档-词矩阵。此时,count_array包含了词频数据,coun_vect.get_feature_names()提供了列名(即词汇)。如果直接使用pd.DataFrame(data=count_array, columns=coun_vect.get_feature_names())创建DataFrame,其行索引将是默认的数字序列,如下所示:
| Hello | I | am | |
|---|---|---|---|
| 0 | 1 | 2 | 1 |
| 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 2 |
而我们期望的结果是,将原始文件名(例如"1905.txt")作为行索引,并且最好能进一步去除文件扩展名,只保留核心信息(如"1905"),使其更简洁明了:
| Hello | I | am | |
|---|---|---|---|
| 1905 | 1 | 2 | 1 |
| 1906 | 1 | 1 | 1 |
| 1907 | 0 | 1 | 2 |
Pandas DataFrame的构造函数提供了一个index参数,允许我们在创建DataFrame时直接指定行索引。这个参数接受一个与数据行数相同长度的列表或数组,其中的元素将作为每一行的标签。
在文件读取阶段,我们通常会收集所有文件的路径。如果这些路径存储在一个有序的列表中(例如corpus),并且其顺序与count_array中的行顺序一致,那么可以直接将这个列表作为index参数的值。
import pandas as pd
from pathlib import Path
from sklearn.feature_extraction.text import CountVectorizer
import re
# 假设文件存储在 'files' 目录下,请替换为您的实际路径
# 例如:'/Users/MyPath/files'
FILE_DIRECTORY = Path("./files")
# 创建一个用于存储文件路径的列表
corpus = []
# 使用 pathlib 遍历指定目录下的所有 .txt 文件
for fichier in FILE_DIRECTORY.rglob("*.txt"):
corpus.append(fichier) # 将 Path 对象直接添加到列表中
# 对文件路径进行排序,确保与后续处理的顺序一致
corpus.sort()
all_documents = []
for fichier_txt_path in corpus:
with open(fichier_txt_path, 'r', encoding='utf-8') as f: # 建议指定编码
fichier_txt_chaine = f.read()
# 清理文本,只保留字母
fichier_txt_chaine = re.sub('[^A-Za-z]', ' ', fichier_txt_chaine)
all_documents.append(fichier_txt_chaine)
# 使用 sklearn 构建文档-词矩阵
coun_vect = CountVectorizer(stop_words="english")
count_matrix = coun_vect.fit_transform(all_documents)
count_array = count_matrix.toarray()
# 方案一:将完整的 Path 对象作为索引
# pd.DataFrame(data=count_array, columns=coun_vect.get_feature_features(), index=corpus)
# 此时索引将是 Path 对象,如 PosixPath('files/1905.txt')通常,我们只关心文件名本身,而不是完整的路径。pathlib.Path对象提供了.name属性,可以直接获取文件名(包含扩展名)。
本文档主要讲述的是Lucene 索引数据库;Lucene,作为一种全文搜索的辅助工具,为我们进行条件搜索,无论是像Google,Baidu之类的搜索引擎,还是论坛中的搜索功能,还 是其它C/S架构的搜索,都带来了极大的便利和比较高的效率。本文主要是利用Lucene对MS Sql Server 2000进行建立索引,然后进行全文索引。至于数据库的内容,可以是网页的内容,还是其它的。本文中数据库的内容是图书馆管理系统中的某个作者表 -Authors表。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看
0
# ... (承接上述代码) ...
# 方案二:将文件名(含扩展名)作为索引
file_names = [f.name for f in corpus]
allDataframe_with_names = pd.DataFrame(data=count_array,
columns=coun_vect.get_feature_names_out(), # 推荐使用 get_feature_names_out()
index=file_names)
print("DataFrame with filenames as index:")
print(allDataframe_with_names.head())在许多情况下,文件扩展名是冗余的,我们只想要文件名的主体部分。pathlib.Path对象还提供了.stem属性,可以方便地获取不包含扩展名的文件名。这对于按年份命名的文件(如"1905.txt")尤为适用,可以直接提取出"1905"。
# ... (承接上述代码) ...
# 方案三:将文件名(不含扩展名)作为索引
file_stems = [f.stem for f in corpus]
allDataframe_with_stems = pd.DataFrame(data=count_array,
columns=coun_vect.get_feature_names_out(),
index=file_stems)
print("\nDataFrame with file stems as index:")
print(allDataframe_with_stems.head())
# 将结果保存到CSV文件
allDataframe_with_stems.to_csv("Matrice_doc_term_with_filenames.csv", index=True) # index=True 确保索引也被写入CSV完整示例代码:
为了使代码可运行,我们创建一个模拟的files目录和一些.txt文件。
import pandas as pd
from pathlib import Path
from sklearn.feature_extraction.text import CountVectorizer
import re
import os
# --- 模拟文件和目录创建 (仅为示例,实际使用时请替换为您的文件路径) ---
# 创建一个临时目录
temp_dir = Path("./temp_text_files")
temp_dir.mkdir(exist_ok=True)
# 创建模拟的 .txt 文件
file_contents = {
"1905.txt": "Hello world, this is the year 1905. A new beginning.",
"1906.txt": "I am here in 1906. The world is changing.",
"1907.txt": "Am I still here? Yes, it's 1907. Life goes on.",
"1908.txt": "Another year, another story. This is 1908.",
}
for filename, content in file_contents.items():
(temp_dir / filename).write_text(content, encoding='utf-8')
# -----------------------------------------------------------------
# 指定文件目录为模拟创建的目录
FILE_DIRECTORY = temp_dir
# 创建一个用于存储文件路径的列表
corpus = []
# 使用 pathlib 遍历指定目录下的所有 .txt 文件
for fichier in FILE_DIRECTORY.rglob("*.txt"):
corpus.append(fichier)
# 对文件路径进行排序,确保与后续处理的顺序一致
corpus.sort()
all_documents = []
for fichier_txt_path in corpus:
with open(fichier_txt_path, 'r', encoding='utf-8') as f:
fichier_txt_chaine = f.read()
# 清理文本,只保留字母
fichier_txt_chaine = re.sub('[^A-Za-z]', ' ', fichier_txt_chaine)
all_documents.append(fichier_txt_chaine)
# 使用 sklearn 构建文档-词矩阵
coun_vect = CountVectorizer(stop_words="english")
count_matrix = coun_vect.fit_transform(all_documents)
count_array = count_matrix.toarray()
# 获取特征名(词汇)
feature_names = coun_vect.get_feature_names_out()
# 方案:将文件名(不含扩展名)作为索引
file_stems = [f.stem for f in corpus]
allDataframe = pd.DataFrame(data=count_array,
columns=feature_names,
index=file_stems)
print("Final DataFrame with file stems as index:")
print(allDataframe)
# 将结果保存到CSV文件,并确保索引也被写入
allDataframe.to_csv("Matrice_doc_term_with_filenames.csv", index=True)
# --- 清理模拟文件和目录 (仅为示例) ---
for filename in file_contents.keys():
(temp_dir / filename).unlink() # 删除文件
temp_dir.rmdir() # 删除目录
# ------------------------------------通过以上方法,我们可以轻松地将原始文件的标识信息作为Pandas DataFrame的行索引,从而构建出更具可读性和分析价值的文档-词矩阵,为后续的数据可视化和深入分析奠定坚实基础。
以上就是Pandas DataFrame:高效利用文件名作为行索引构建文档-词矩阵的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号