我正在尝试从语料库创建一个依赖解析器。语料库采用 conll 格式,因此我有一个函数可以读取文件并返回列表列表,其中每个列表都是一个已解析的句子(我正在使用的语料库已经解析,我的工作是在这个中找到另一个替代方案解析)。我的教授要求仅随机选取该语料库中 5% 的句子,因为它太大了。
我尝试创建一个空列表并使用附加功能,但我不知道如何通过索引指定我想要语料库的每 100 个句子中的 5 个
我为转换 conll 文件所做的函数如下:
import os, nltk, glob
def read_files(path):
"""
Function to load Ancora Dependency corpora (GLICOM style)
path = full path to the files
returns de corpus in sentences
each sentence is a list of tuples
each tuple is a token with the follwoing info:
index of the token in the sentence
token
lemma
POS /es pot eliminar
POS
FEAT /es pot eliminar
head
DepRelation
"""
corpus = []
for f in glob.glob(path):
sents1 = open(f).read()[185:-2].split('\n\n')
sents2 = []
for n in range(len(sents1)):
sents2.append(sents1[n].split('\n'))
sents3 = []
for s in sents2:
sent = []
for t in s:
sent.append(tuple(t.split('\t')))
sents3.append(sent)
corpus.extend(sents3)
return corpus
我想要一种从语料库中每 100 个句子中选择 5 个句子的方法,这样我就可以得到一个仅包含这些句子的列表列表。 提前致谢!
最佳答案
只需使用random.sample
:
# define path here
corpus = read_files(path)
random.sample(corpus, len(corpus) // 20)
关于python - 是否可以创建一个由另一个列表的一定百分比元素组成的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55452867/