【问题标题】:How to find words that have no characters of an string?如何找到没有字符串字符的单词?
【发布时间】:2015-02-08 19:01:50
【问题描述】:

我的问题与 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”。并期望有“朋友”一次而不是两次。 我该如何解决我的问题?

【问题讨论】:

  • 您需要存储您已经printed 的words,并确保您不再print它们。
  • 哪一部分你不明白?
  • @Stack Over Hello 问题解决了
  • 哎呀。 @jonrsharpe 问题解决了

标签: string python-2.7 character-arrays


【解决方案1】:

将它们放在一组以消除欺骗。然后,对于每个要打印的单词,只有 all 个字母没有出现在单词中。像这样的:

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

【讨论】:

  • 非常感谢。它的工作。甚至它会从最后一个到第一个打印单词。
  • 顺序不是确定的,取决于集合的顺序。您可能希望使用 sorted 来按字典顺序对它们进行排序,或者使用某种有序集合来按条目顺序进行排序。
猜你喜欢
  • 1970-01-01
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多