【问题标题】:How can I add filename of imported txt files to dataframe in python如何将导入的txt文件的文件名添加到python中的数据框
【发布时间】: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


【解决方案1】:

这应该可行。它从文件名中获取数字。

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})

【讨论】:

  • 感谢您的回答。这是工作。但我只想要数值作为文件名,范围从 3 到 4 位(100、1001 等)。目前,我得到的文件名只有 3 位数字。有什么办法可以在代码中容纳这个(3 位和 4 位数字)?
  • 我已更新代码以从文件名中选择数值。它现在可以选择任何长度
【解决方案2】:

有一个单行:

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)

【讨论】:

  • aah 我看你只是想要数字....我会修改
  • 感谢您的回答。我也收到此代码的此错误:ParserError: Error tokenizing data. C error: Expected 1 fields in line 48, saw 2
  • 错误继续:ParserError: Error tokenizing data. C error: Expected 1 fields in line 48, saw 2
  • 来自一些谷歌搜索......看起来你可能想在read_csv, comment='#' 中传递, error_bad_lines=False 对不起,但我不知道错误是什么。这个对我有用。以下是一些链接:stackoverflow.com/questions/18039057/…stackoverflow.com/questions/49632641/…
猜你喜欢
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 2020-10-06
相关资源
最近更新 更多