是否可以创建一个由另一个列表的元素百分比组成的列表?

2024-09-30 08:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个语料库创建一个依赖解析器。语料库是conll格式的,所以我有一个函数读取文件并返回列表列表,其中每个列表都是一个经过解析的句子(我使用的语料库已经被解析了,我的工作是在这个解析中找到另一个替代方法)。我的教授要求随机选取这个语料库中5%的句子,因为它太大了。你知道吗

我试过创建一个空列表并使用append函数,但是我不知道如何通过索引来指定我想要语料库中每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个句子,这样我就可以有一个只包含这些句子的列表。 提前谢谢!你知道吗


Tags: thepathintoken列表forcorpusglob
2条回答

你能给列表添加一个循环吗?像这样使用模数运算符“%”的话,100个句子中只能得到5个:

counter = 0
new_list =[]
for i in my_list:
  counter = counter +1 
  if counter % 20 ==0:
       new_list.append(i)
  else:
       continue 

只需使用random.sample

# define path here
corpus = read_files(path)

random.sample(corpus, len(corpus) // 20)

相关问题 更多 >

    热门问题