python怎么后退,使用python循环后退一步和前进一步

I need to loop in a list containing french words and find an asterisk because I want to concatenate the word before the asterisk and the word after the asterisk each time an asterisk appear and continue to the next.

For example, in the sequence:

['les','engage', '*', 'ment', 'de','la']

I want to concatenate 'engage' and 'ment' and the output (engagement) should be checked by a dictionary. If in the dictionary, append to a list.

With my code I only get the asterisk:

import nltk

from nltk.tokenize import word_tokenize

import re

with open ('text-test.txt') as tx:

text =word_tokenize(tx.read().lower())

with open ('Fr-dictionary.txt') as fr:

dic = word_tokenize(fr.read().lower())

ast=re.compile(r'[\*]+')

regex=list(filter(ast.match,text))

valid_words=[]

invalid_words=[]

last = None

for w in text:

if w in regex:

last=w

a=last + w[+1]

break

if a in dic:

valid_words.append(a)

else:

continue

解决方案

I wondered how to manage a list (nonsense) like this:

words = ['Bien', '*', 'venue', 'pour', 'les','engage', '*', 'ment', 'trop', 'de', 'YIELD', 'peut','être','contre', '*', 'productif' ]

So I came u with a method like this:

def join_asterisk(ary):

i, size = 0, len(ary)

while i < size-2:

if ary[i+1] == '*':

yield ary[i] + ary[i+2]

i+=2

else: yield ary[i]

i += 1

if i < size:

yield ary[i]

Which returns:

print(list(join_asterisk(words)))

#=> ['Bienvenue', 'pour', 'les', 'engagement', 'trop', 'de', 'YIELD', 'peut', 'être', 'contreproductif']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值