|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
例如,给一段:
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had
everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way—in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.
如何写一个方程,找到一个特定单词所有前一个单词长度的总和?例如输入 "the", 前面的单词从一开始有 was , was, ... short,.... in. 如何找出这些单词并对长度进行加和呢?
谢谢
没那么麻烦的,几句搞定~
- >>> def preword(word,txt):
- words_ls = txt.split()
- rslt = [words_ls[i-1]for i,w in enumerate(words_ls)if w==word]
- return len(''.join(rslt)),rslt
- >>> preword('the',txt)
- (48, ['was', 'was', 'was', 'was', 'was', 'was', 'was', 'was', 'was', 'was', 'direct', 'short,', 'like', 'in'])
- >>>
复制代码
|
|