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.
所以,請調整你的大腦,並幫助我解決方案...
我非常感謝任何答覆!
非常感謝您提前!