我正在尝试编写一个简单的 if 语句,该语句取决于一组条件(列表中的出现次数为 0),但是当我的两个条件均为 0 时,我遇到了错误,只有一个语句是显示。
if let1 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
elif let2 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
elif let3 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")
我尝试过使用 or 语句,但无法生成所需的输出,通知用户他们的一个、两个或三个输入可能不在我的程序其余部分使用的文本正文中。
对于缺乏简洁的术语表示歉意,因为我对编程非常陌生。
谢谢
编辑:谢谢您的回复,但我应该给出完整的功能......
def segment_sequence(mycorpus, letter1, letter2, letter3):
corpus_string = "".join(mycorpus)
a = letter1
b = letter2
c = letter3
d = a + b
e = b + c
let1 = corpus_string.count(a)
let2 = corpus_string.count(b)
let3 = corpus_string.count(c)
let1let2 = corpus_string.count(d)
let2let3 = corpus_string.count(e)
print(let1,let2,let3)
if let1 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
if let2 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
if let3 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")
break
else:
trans_prob1 = let1let2/let1
trans_prob2 = let2let3/let2
if trans_prob1 > trans_prob2:
print('Here is the proposed boundary given the training corpus:\n')
print('Proposed end of one word:' ,d,'\n')
print('Proposed beginning of new word:' ,c,'\n')
elif trans_prob2 > trans_prob1:
print('Here is the proposed boundary given the training corpus:\n')
print('Proposed end of one word: ',e,'\n')
print('Proposed beginning of new word: ',a,'\n')
elif trans_prob1 == trans_prob2:
print('Both ',d,' and ',e,' are equally possible word endings')
return()
使用 if 而不是 elif 的问题是它不会中断,然后我会收到除以 0 的错误。我不是在寻找任何太复杂的东西,只是简单而准确的用户错误消息。
再次感谢
最佳答案
不要使用elif
,而是尝试使用if
,如下所示:
if let1 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",a, "\n")
if let2 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",b, "\n")
if let3 == 0:
print("Segmentation unavailable as corpus does not contain the following letter ",c, "\n")
关于python - 压缩 if 语句以提供更准确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451233/