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

标签 python regex file dictionary split

我有一个文本文件,其中包含以下几行,我想将它们分成每个句子的列表,一个句子是 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/

相关文章:

python - 访问 Python egg 中的配置文件时出现问题

python - Pandas :AttributeError: 'module' 对象没有属性 '__version__'

python - 是否可以与 python pandas 进行模糊匹配合并?

r - 在字符串中用 $ grep

正则表达式多条件

git - 如何从 git 存储库中只稀疏地 check out 一个文件?

python - 为什么 Python 模块有时不导入它们的子模块?

python - 通过 pywinauto 上的位置获取控制

javascript - 如何从 html 字符串中获取 head 和 body 标签作为字符串?

java - Android:在文件中定位(类似于C++中的fseek)?