【问题标题】:list of lists.. of lists? Applying regex and nltk列表列表..列表?应用正则表达式和 nltk
【发布时间】:2019-02-15 03:26:55
【问题描述】:

好的,我简化我的问题:

我有一个列表(文档),其中包含一些列表(句子)作为str。赞a = [['Sent1 from first doc!','Sent2 from first doc.'],['Sent1 from 2nd doc.','Sent2 from 2nd doc.']]

现在我尝试将每个句子分成一个单词列表。所以我可能会有一个包含一个列表(句子)的第一个(文档)列表,其中每个包含一个列表(该句子中的单词)作为str)。

不幸的是,我的代码生成了一个包含每个单词的(句子)列表。因此,我忘记了每个句子来自哪个文档。

我的代码如下所示:

sentcs = []
for i in range(len(a)): 
    for p in range(len(a[i])):        
        spr = re.findall(r'[A-Z]?[^A-Z\s]+|[A-Z]+', a[i][p])
        sentcs.append(spr) 

但这不是我想要的..我想要一个列表列表..或者是编写这样的程序的坏习惯?

【问题讨论】:

    标签: python regex python-3.x list nltk


    【解决方案1】:
        li = [('Help! Be nice.'),('Thx. Help appreciated.')]
    
        for el in li:
            l = el.split(' ',1)
            print(tuple((l[0], l[1:])))  
    
        ('Help!', ['Be nice.'])
        ('Thx.', ['Help appreciated.'])
    
    
    from nltk.tokenize import sent_tokenize   
    
    st = ['Help! Be nice.','Thx. Help appreciated.']
    
    for el in st:
        t = sent_tokenize(el)
        print(tuple((t[0], t[1:])))
    
    ('Help!', ['Be nice.'])
    ('Thx.', ['Help appreciated.'])
    

    【讨论】:

    • 对不起,我犯了一个错误:我确实从一个列表开始,但是一个字符串列表 'string=['Help!很好。','谢谢。帮助赞赏。']'因此,在第二步中,我有一个看起来像'string = [['Help!','Be nice'],[Thx.','Help赞赏']]'的列表我需要将其进一步拆分为另一个列表,但我上面的代码只是创建了一个列表,其中包含所有拆分为单词的句子,因此我丢失了它所属的文档的信息
    猜你喜欢
    • 2019-07-04
    • 1970-01-01
    • 2013-11-24
    • 2011-10-05
    • 2012-09-02
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多