gpt4 book ai didi

python - 将大文本文件拆分为句子

转载 作者:行者123 更新时间:2023-11-30 23:29:09 25 4
gpt4 key购买 nike

我有一个文本文件,其中包含以下几行,我想将它们分成每个句子的列表,一个句子是 1-5,另一个句子是 1-8,依此类推,每个句子之间有空格。例如,一个句子列表应该是['Den', 'allmänna','pensionen', 'är', 'av'],即1-5

from collections import defaultdict

out = defaultdict(list) # Initialize dictionary for output
key = 0 # Initialize key

for idx, word, _ in container: # Unpack sublists
if int(idx) == 1: # Check if we are at start of new sentence
key += 1 # Increment key for new sentence
out[key].append(word) # Add word to list

How to slice numbered lists into sublists

代码运行良好,但是当我尝试直接从测试文件将其应用到分割行时,我得到ValueError 表示有太多值无法解压。该文件总共包含 87 行。我想使用上面的代码,但不知道如何解决 ValueError。

1   Den     DT  DT  UTR|SIN|DEF 3   DT  _   _   _   _   P108_1:1
2 allmänna JJ JJ POS|UTR/NEU|SIN|DEF|NOM 3 AT _ _ _ _ P108_1:2
3 pensionen NN NN UTR|SIN|DEF|NOM 4 SS _ _ _ _ P108_1:3
4 är VB VB PRS|AKT 0 ROOT _ _ _ _ P108_1:4
5 av PP PP 4 SP _ _


1 Folkpensionen NN NN UTR|SIN|DEF|NOM 2 OO _ _ _ _ P108_2:1
2 får VB VB PRS|AKT 0 ROOT _ _ _ _ P108_2:2
3 man PN PN UTR|SIN|IND|SUB 2 SS _ _ _ _ P108_2:3
4 oberoende PC PC PRS|UTR/NEU|SIN/PLU|IND/DEF|NOM 2 AA _ _ _ _ P108_2:4
5 av PP PP 4 HD _ _
6 tidigare JJ JJ KOM|UTR/NEU|SIN/PLU|IND/DEF|NOM 7 DT _ _ _ _ P108_2:6
7 arbetsinkomst NN NN UTR|SIN|IND|NOM 4 PA _ _ _ _ P108_2:7
8 . MAD MAD 2 IP _ _

最佳答案

使用itertools.groupby并使用str.isspace对项目进行分组:

from itertools import groupby

with open('abc1') as f:
for k, g in groupby(f, str.isspace):
if not k:
sentence = [x.split(None, 2)[1] for x in g]
print sentence

输出:

['Den', 'allm\xc3\xa4nna', 'pensionen', '\xc3\xa4r', 'av']
['Folkpensionen', 'f\xc3\xa5r', 'man', 'oberoende', 'av', 'tidigare', 'arbetsinkomst', '.']

关于python - 将大文本文件拆分为句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21261218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com