虽然通常很难准确判断句子的结束位置,但在这种情况下,每个句子都有句号标记结尾,因此我们可以使用它来将段落拆分为句子。您已经有了将其拆分为单词的代码,但这里是:
paragraph = "Lorem Ipsum ... "
sentences = []
while paragraph.find('.') != -1:
index = paragraph.find('.')
sentences.append(paragraph[:index+1])
paragraph = paragraph[index+1:]
print sentences
输出:
['Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
'It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.',
'It was popularised in the 1960s with the release of Letraset sheets containing.',
'Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.']
然后我们将它们全部转换为单词数组:
word_matrix = []
for sentence in sentences:
word_matrix.append(sentence.strip().split(' '))
print word_matrix
哪些输出:
[['Lorem', 'Ipsum', 'is', 'simply', 'dummy', 'text', 'of', 'the', 'printing', 'and', 'typesetting', 'industry.'],
['Lorem', 'Ipsum', 'has', 'been', 'the', "industry's", 'standard', 'dummy', 'text', 'ever', 'since', 'the', '1500s,', 'when', 'an', 'unknown', 'printer', 'took', 'a', 'galley', 'of', 'type', 'and', 'scrambled', 'it', 'to', 'make', 'a', 'type', 'specimen', 'book.'],
['It', 'has', 'survived', 'not', 'only', 'five', 'centuries,', 'but', 'also', 'the', 'leap', 'into', 'electronic', 'typesetting,', 'remaining', 'essentially', 'unchanged.'],
['It', 'was', 'popularised', 'in', 'the', '1960s', 'with', 'the', 'release', 'of', 'Letraset', 'sheets', 'containing.'],
['Lorem', 'Ipsum', 'passages,', 'and', 'more', 'recently', 'with', 'desktop', 'publishing', 'software', 'like', 'Aldus', 'PageMaker', 'including', 'versions', 'of', 'Lorem', 'Ipsum.']]