我创建了一个函数,它接受一个单词和一串'禁止'字母,如果单词不使用任何字母,则返回True。
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
else:
return True
我想修改它,而不是使用'forbidden'作为要避免的字母,将提示用户放置几个字母并打印不包含任何字母的单词数。我还有一个包含这些单词的.txt文档,以使其变得有趣。
这就是我想出来的错误。如果可能的话,我希望得到一些帮助和教育,因为我的“在线”老师永远不会提供帮助。请帮助:)
def word_no_forbidden():
forbidden = input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in word:
if forbidden in word:
continue
print word
这是我得到的错误,我理解但是,我不确定如何处理这个......
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
word_no_forbidden()
File "C:/Python27/test.py", line 9, in word_no_forbidden
if forbidden in word:
TypeError: 'in <string>' requires string as left operand, not tuple
答案 0 :(得分:2)
我的猜测......
你是python 2.x
运行您输入的程序时:
'a','b','c','d'
在python 2.x上,你想使用raw_input而不是输入。这将给出一个你输入的字符串。因为它是python将尝试解释你正确的python表达式,这是危险的,通常是一个坏主意。
您的第二个问题是,您已从第一个示例letter in forbidden
撤消了您的代码行,因此它变为forbidden in word
不一样。
答案 1 :(得分:2)
def word_no_forbidden():
forbidden = raw_input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in list(word):
if letter in forbidden:
break
else:
print word
注意:强>
1&GT;正如温斯顿所说,使用raw_input
2 - ;如果您想遍历字符串,请使用list(your_string)
获取字符列表
3&GT;这里else
仅在我们的for letter in list(word)
循环完成时才会执行而不会中断(换句话说,没有任何字母被禁止)
答案 2 :(得分:1)
要读取用户的字符串,您应该使用raw_input
,而不是input
。 input
尝试实际评估用户键入的字符串作为Python代码,并且可能导致您获得您不期望的数据类型(或其他更糟糕的事情)。
相反,raw_input
总是返回一个字符串。
(注意:这仅适用于Python 2.x.从Python 3开始,raw_input
被重命名为input
,并且没有执行input
过去的功能。 )
答案 3 :(得分:1)
在代码的这一部分
for letter in word:
if forbidden in word:
你应该这样做
for letter in forbidden:
if letter in word:
您要做的是检查用户输入的每个字母,如果它是从文件中读取的单词,请跳过该单词并转到下一个单词。有更多的pythonic方法可以做到这一点,但我认为这很清楚,也很容易理解。