Python 嵌套循环的问题…;
我将向您详细解释我想要实现的目标。Python 嵌套循环的问题…;,python,Python,我将向您详细解释我想要实现的目标。 我有两个关于词典的程序。 程序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 wor
我有两个关于词典的程序。
程序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))
该计划有以下优点:
- 你可以写多个句子
- 第一个字母在“.”之后大写
- 程序将未翻译的单词“附加”到输出(“translation=[])
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 我希望输出为:
Jeg leste boka. Jeg leste boka! Jeg leste boka? Jeg leste boka.
所以,请调整你的大脑,帮我找到一个解决方案…非常感谢您的回复
提前非常感谢 我的解决方案流程如下:
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字,而不是使用该位置变量
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