我的文字是这样的:
text = "All human beings are born free and equal in dignity and rights. They are endowed with reason and conscience and should act towards one another in a spirit of brotherhood."
如何编写处理文本的函数对冲(文本)并生成一个在文本的每三个单词中插入“like”一词的新版本?
结果应该是这样的:
text2 = "All human beings like are born free like and equal in like..."
谢谢!
答案 0 :(得分:3)
而不是给你一些像
solution=' like '.join(map(' '.join, zip(*[iter(text.split())]*3)))
我发布了关于如何解决问题的一般建议。 “算法”并不是特别“pythonic”,但希望很容易理解:
words = split text into words
number of words processed = 0
for each word in words
output word
number of words processed += 1
if number of words processed is divisible by 3 then
output like
如果您有任何疑问,请告诉我们。
答案 1 :(得分:1)
你可以选择这样的东西:
' '.join([n + ' like' if i % 3 == 2 else n for i, n in enumerate(text.split())])