3

我对python语言相当陌生,我一直在寻找这个问题的答案。

我需要一个看起来像这样的列表:

['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.']

转换为如下所示的字符串:

Kevin went to his computer.

He sat down.

He fell asleep.

我需要它的字符串格式,所以我可以将它写入一个文本文件。任何帮助,将不胜感激。

4

1 回答 1

4

简短的解决方案:

>>> l
['Kevin', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.']

>>> print ' '.join(l)
Kevin went to his computer. He sat down. He fell asleep.

>>> print ' '.join(l).replace('. ', '.\n')
Kevin went to his computer.
He sat down.
He fell asleep.

长解决方案,如果您想确保只有单词末尾的句点触发换行符:

>>> l
['Mr. Smith', 'went', 'to', 'his', 'computer.', 'He', 'sat', 'down.', 'He', 'fell', 'asleep.'] 
>>> def sentences(words):
...     sentence = []
... 
...     for word in words:
...         sentence.append(word)
... 
...         if word.endswith('.'):
...             yield sentence
...             sentence = []
... 
...     if sentence:
...         yield sentence
... 
>>> print '\n'.join(' '.join(s) for s in sentences(l))
Mr. Smith went to his computer.
He sat down.
He fell asleep.
于 2012-11-29T00:27:25.103 回答