我正在尝试将一个文本文件拆分成单词,\n
被视为一个单词。
我的输入是这个文本文件:
War and Peace
by Leo Tolstoy/Tolstoi
我希望您能输出类似以下格式的列表: ```` ````
['War','and','Peace','\n','\n','by','Leo','Tolstoy/Tolstoi']
使用
.split()
我得到了这个结果:['War', 'and', 'Peace\n\nby', 'Leo', 'Tolstoy/Tolstoi']
所以我开始编写程序,在单词后将 \n 作为单独的条目添加,代码如下:
for oldword in text:
counter = 0
newword = oldword
while "\n" in newword:
newword = newword.replace("\n","",1)
counter += 1
text[text.index(oldword)] = newword
while counter > 0:
text.insert(text.index(newword)+1, "\n")
counter -= 1
然而,程序似乎在
counter -= 1
这一行卡住了,我真的想不出为什么。注意:我意识到如果这样做可以成功,结果将是 ['Peaceby',"\n","\n"];这是另一个待解决的问题。
for oldword in text:
下面吗? - Eugene K'Peace\n\nby'
。 - Padraic Cunninghamsplit(' ')
,就会这样做。也许这就是 OP 的意思。 - tdelaney