-4

我有这样的文字:

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."

如何编写一个函数 hedging(text) 来处理我的文本并生成一个新版本,在文本的每三个单词中插入单词“like”?

结果应该是这样的:

text2 = "All human beings like are born free like and equal in like..."

谢谢!

4

2 回答 2

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

如果您有任何问题,请告诉我们。

于 2013-04-03T07:44:05.590 回答
1

你可以用这样的东西:

' '.join([n + ' like' if i % 3 == 2 else n for i, n in enumerate(text.split())])
于 2013-04-03T07:40:17.213 回答