2010-03-01 161 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個單詞,而不是使用該位置變量。