首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将文件夹中的多个ann文件(从brat注解)读取到一个pandas数据帧中?

如何将文件夹中的多个ann文件(从brat注解)读取到一个pandas数据帧中?
EN

Stack Overflow用户
提问于 2021-08-16 22:38:32
回答 1查看 108关注 0票数 0

我可以将一个ann文件读入pandas dataframe,如下所示:

代码语言:javascript
复制
df = pd.read_csv('something/something.ann', sep='^([^\s]*)\s', engine='python', header=None).drop(0, axis=1)
df.head()

但我不知道如何将多个ann文件读取到一个pandas数据帧中。我尝试使用concat,但结果并不是我所期望的。

如何将多个ann文件读入一个pandas数据帧?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-16 23:16:59

听起来您需要使用glob从一个文件夹中提取所有.ann文件,并将它们添加到数据帧列表中。在此之后,您可能希望根据需要加入/merge/concat等。

我不知道您的确切要求,但下面的代码应该可以让您更接近。正如脚本假设的那样,在您运行Python脚本的位置,您有一个名为files的子文件夹,您希望在其中拉入所有的.ann文件(它不会查看任何其他内容)。显然,根据每一行的注释,根据需要进行检查和更改。

代码语言:javascript
复制
import pandas as pd
import glob

path = r'./files' # use your path
all_files = glob.glob(path + "/*.ann")

# create empty list to hold dataframes from files found
dfs = []

# for each file in the path above ending .ann
for file in all_files:
    #open the file
    df = pd.read_csv(file, sep='^([^\s]*)\s', engine='python', header=None).drop(0, axis=1)
    #add this new (temp during the looping) frame to the end of the list
    dfs.append(df)

#at this point you have a list of frames with each list item as one .ann file.  Like [annFile1, annFile2, etc.] - just not those names.

#handle a list that is empty
if len(dfs) == 0:
    print('No files found.')
    #create a dummy frame
    df = pd.DataFrame()
#or have only one item/frame and get it out
elif len(dfs) == 1:
    df = dfs[0]
#or concatenate more than one frame together
else: #modify this join as required.
    df = pd.concat(dfs, ignore_index=True)
    df = df.reset_index(drop=True)

#check what you've got
print(df.head())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68809899

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档