【问题标题】:Is it possible to create a list consisting of a percentage of elements of another list?是否可以创建一个由另一个列表的元素百分比组成的列表?
【发布时间】:2019-08-22 11:40:30
【问题描述】:

我正在尝试从语料库创建依赖解析器。语料库是 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 个句子的方法,这样我就可以得到一个仅包含这些的列表。 提前致谢!

【问题讨论】:

标签: python nlp


【解决方案1】:

只需使用random.sample:

# define path here
corpus = read_files(path)

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

【讨论】:

    【解决方案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 
    

    【讨论】:

    • 我可能做错了什么,我将它添加到我的循环中,我得到了这种类型的错误:只能将列表(不是“int”)连接到列表
    • 我不知道为什么会这样。我猜这与输入列表格式有关?玩弄我无法重现该错误。您是否在某处做这样的事情:[list_1] +[list_2] 如果是这样,可能是它
    • 在您编写的代码中,我将 my_list 更改为 corpus,这是我的列表变量的名称。其余的我复制到我的函数定义中。明天我会问我的老师,我可以告诉你我的错误是什么
    • 好的,看过上面的代码后,我相信问题将来自corpus.extend(sents3),也许试试corpus.append(sents3)? python处理extendappend的方式有区别stackoverflow.com/questions/252703/…
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2021-08-24
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多