使用python循环后退一步和前进一步 [英] go one step back and one step forward in a loop with python

查看:208
本文介绍了使用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'] 

我要连接接合"和"ment",并且输出(接合)应由字典检查.如果在字典中,请追加到列表中.

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]

哪个返回:

print(list(join_asterisk(words)))
#=> ['Bienvenue', 'pour', 'les', 'engagement', 'trop', 'de', 'YIELD', 'peut', 'être', 'contreproductif']

这篇关于使用python循环后退一步和前进一步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆