我有一个包含以下行的文本文件,我想将它们分成每个句子的列表,一个句子是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
代码运行良好,但是当我尝试直接从testfile中将它应用于分割线时,我得到了 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 _ _
答案 0 :(得分:3)
使用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', '.']