如何找到没有字符串字符的单词?

时间:2014-12-10 14:26:33

标签: string python-2.7 character-arrays

我的问题与python有关。我有一个包含一些文本的.txt文件。我希望有一个代码,提示用户输入禁止字母串,然后打印文件中不包含任何字的单词数。我写了这个:

letters=raw_input("Please enter forbidden letters")
text=open("p.txt", "r").read().split()
for word in text:
   for i in letters:
       if not j in word:
          print word

也有这个:

letters=raw_input("Please enter forbidden letters")
text=open("p.txt", "r").read().split()
for word in text:
   for i in letters:
       for j in i:
           if not j in word:
               print word

但是这两个代码都给了我不包含每个字符而不是所有字符的单词。例如,如果我的文件有“Hello good friends”并且用户输入“oh”,则此代码打印:

您好 好 朋友 朋友

但我希望只有“朋友”没有,“o”不是“h”。并希望有一次而不是两次“朋友”。 我该如何解决我的问题?

1 个答案:

答案 0 :(得分:1)

将它们放入一套以移除欺骗。然后,只有当所有字母没有出现在单词中时,才能打印每个单词。像这样:

letters = raw_input("Please enter forbidden letters")
words = set(open("p.txt", "r").read().split())
for word in words:
  if all(letter not in word for letter in letters):
    print word