如何在Python中将导入的txt文件的文件名添加到数据框中?

17 浏览
0 Comments

如何在Python中将导入的txt文件的文件名添加到数据框中?

我已经从一个文件夹导入了几千个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})

admin 更改状态以发布 2023年5月21日
0
0 Comments

这是一个一行代码:

df = pd.concat([pd.read_csv(f, encoding='latin-1').
                assign(Filename=os.path.basename(f)) for f in glob.glob('K:\\text_all*.txt')])
df['Filename'] = df['Filename'].str.extract('(\d+)').astype(int)

0
0 Comments

这应该可以工作。它会从文件名中获取数字。

import glob
import os
import pandas as pd
file_list = glob.glob(os.path.join(os.getcwd(), "K:\\text_all", "*.txt"))
corpus = []
files = []
for file_path in file_list:
    with open(file_path, encoding="latin-1") as f_input:
        corpus.append(f_input.read())
        files.append(''.join([n for n in os.path.basename(file_path) if n.isdigit()]))
df = pd.DataFrame({'file':files, 'text':corpus})

0