【发布时间】:2020-11-03 09:19:31
【问题描述】:
我已将几千个 txt 文件从一个文件夹导入到 pandas dataframe。有什么方法可以创建一个列,从其中导入的 txt 文件的文件名中添加一个子字符串?这是通过唯一的名称来标识数据框中的每个文本文件。
文本文件被命名为1001example.txt, 1002example.txt, 1003example.txt 和儿子。我想要这样的东西:
filename text
1001 this is an example text
1002 this is another example text
1003 this is the last example text
....
我用来导入数据的代码如下。但是,我不知道如何通过文件名的子字符串创建列。任何帮助,将不胜感激。谢谢。
import glob
import os
import pandas as pd
file_list = glob.glob(os.path.join(os.getcwd(), "K:\\text_all", "*.txt"))
corpus = []
for file_path in file_list:
with open(file_path, encoding="latin-1") as f_input:
corpus.append(f_input.read())
df = pd.DataFrame({'text':corpus})
【问题讨论】:
标签: python python-3.x pandas dataframe