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.
所以,请调整你的大脑,并帮助我解决方案...
我非常感谢任何答复!
非常感谢您提前!