2010-03-01 174 views
1

我将向您详细解释我想实现的目标。
我有2个关于字典的程序。
方案1中的代码是在这里:嵌套循环的问题...

import re 
words = {'i':'jeg','am':'er','happy':'glad'} 

text = "I am happy.".split() 
translation = [] 

for word in text: 
    word_mod = re.sub('[^a-z0-9]', '', word.lower()) 
    punctuation = word[-1] if word[-1].lower() != word_mod[-1] else '' 
    if word_mod in words: 
     translation.append(words[word_mod] + punctuation) 
    else: 
     translation.append(word) 
translation = ' '.join(translation).split('. ') 
print('. '.join(s.capitalize() for s in translation)) 

这个程序有以下优点:“”

  • 你可以写一个以上的句子
  • 你得到的第一个字母后大写
  • 程序“追加”的非翻译字到输出(“翻译= []”)

下面是节目2的代码:

words = {('i',): 'jeg', ('read',): 'leste', ('the', 'book'): 'boka'} 
max_group = len(max(words)) 

text = "I read the book".lower().split() 
translation = [] 

position = 0 
while text: 
    for m in range(max_group - 1, -1, -1): 
     word_mod = tuple(text[:position + m]) 
     if word_mod in words: 
      translation.append(words[word_mod]) 
      text = text[position + m:] 
    position += 1 

translation = ' '.join(translation).split('. ') 
print('. '.join(s.capitalize() for s in translation)) 

有了这个代码可以翻译的习惯用语或
“书”到“博卡”。
这是程序如何执行代码。
这是输出:

 
1 
('i',) 
['jeg'] 
['read', 'the', 'book'] 
0 
() 
1 
('read', 'the') 
0 
('read',) 
['jeg', 'leste'] 
['the', 'book'] 
1 
('the', 'book') 
['jeg', 'leste', 'boka'] 
[] 
0 
() 
Jeg leste boka 

我要的是执行一些代码从程序1到程序2.
我都没有成功尝试了很多次......
这里是我的梦想...:
如果我改变文字下面...:

text = "I read the book. I read the book! I read the book? I read the book.".lower().split() 

我所要的输出是:

Jeg leste boka. Jeg leste boka! Jeg leste boka? Jeg leste boka. 

所以,请调整你的大脑,并帮助我解决方案...
我非常感谢任何答复!
非常感谢您提前!

回答

0

我的解决方案流程是这样的:

dict = ... 
max_group = len(max(dict)) 
input = ... 
textWPunc = input.lower().split() 
textOnly = [re.sub('[^a-z0-9]', '', x) for x in input.lower().split()] 
translation = [] 

while textOnly: 
    for m in [max_group..0]: 
     if textOnly[:m] in words: 
      check for punctuation here using textWPunc[:m] 
      if punctuation present in textOnly[:m]: 
       Append translated words + punctuation 
      else: 
       Append only translated words 
      textOnly = textOnly[m:] 
      textWPunc = textWPunc[m:] 

join translation to finish 

的关键部分是你保持文本的两条平行线,你检查的话翻译,如果你的翻译等你检查标点符号一个搜索带来一击。为了检查标点符号,我将我正在检查的单词组输入到re()中,如下所示:re.sub('[a-z0-9]', '', wordGroup)这将删除所有字符,但不包含标点符号。

最后一件事是,您的索引看起来有点奇怪,我位置变量。由于您正在截断源字符串,因此我不确定这是否真的有必要。只需检查最左边的x个单词,而不是使用该位置变量。