Python—文本文件读入数据帧,然后附加部分文件名

Python—文本文件读入数据帧,然后附加部分文件名,python,dataframe,append,Python,Dataframe,Append,获取了多个文件名为的txt文件,提供了它包含的主题。我需要使用glob读取文件,然后创建一个包含2列的数据框,1-contents和2-topic name(取自文件名) 输出: content topicName 0 .\54468 1 .\54468 2 In article

获取了多个文件名为的txt文件,提供了它包含的主题。我需要使用glob读取文件,然后创建一个包含2列的数据框,1-contents和2-topic name(取自文件名)

输出:

content topicName
0                                                       .\54468
1                                                       .\54468
2   In article <sheafferC63zt0.Brs@netcom.com shea...   .\54468
3                                                       .\54468
4                                                       .\54468
5                                                       .\54468
6   It had to happen: the old allegation of the "d...   .\54468
我如何做到这一点

类似于:

import pandas as pd
import glob as gb

def process_file(file):
    with open(file, "r") as f:
        content = f.read()
        topic = file.split('_1')[0] 
        return {"content": content, "topicname": topic}

data = [process_file(file) for file in gb.glob('./*_1*')]

df = pd.DataFrame(data)

使用
os.path.basename
获取文件名,然后使用
str.split

Ex:

import glob
import os
import pandas as pd
res = []
for name in gb.glob('./*_1*'):
    with open(name, "r") as f1:
        res.append({'content':f1.read(), "topicname": os.path.basename(name).split('_1')[0]})
df = pd.DataFrame(res)
print(df) 
import pandas as pd
import glob as gb

def process_file(file):
    with open(file, "r") as f:
        content = f.read()
        topic = file.split('_1')[0] 
        return {"content": content, "topicname": topic}

data = [process_file(file) for file in gb.glob('./*_1*')]

df = pd.DataFrame(data)
import glob
import os
import pandas as pd
res = []
for name in gb.glob('./*_1*'):
    with open(name, "r") as f1:
        res.append({'content':f1.read(), "topicname": os.path.basename(name).split('_1')[0]})
df = pd.DataFrame(res)
print(df)