繁体   English   中英

如何打印不包含特定字母字符串的单词?

[英]how to print words excluding particular letter string?

我需要编写一个程序来提示用户输入一串禁止的字母,然后打印不包含任何字母的单词数

这就是我所拥有的:

fin=open("demo.txt",'r')
letters=str(raw_input("Enter the key you want to exclude"))
def avoid ():   
    for line in fin:
        word = line.strip()
        for l in letters:
            if l not in word: 
                print word          
avoid()

如果我使用in关键字,它将打印具有特定字符串的所有单词。 但是当我使用not in时,它的工作方式不同。

这样的事情应该起作用:

for l in letters:
    if l in word:
        break  # we found the letter in the word, so stop looping
else:
    # This will execute only when the loop above didn't find
    # any of the letters. 
    print(word)

最简单的方法是将字母组合在一起,将每一行拆分成单词,然后求和多少次没有禁止字母的单词:

with open("demo.txt", 'r') as f:
    letters = set(raw_input("Enter the key you want to exclude"))
    print(sum(not letters.intersection(w) for line in f for w in line.split()))

您还可以使用str.translate ,检查翻译后字长是否已更改:

with open("demo.txt", 'r') as f:
    letters = raw_input("Enter the key you want to exclude")
    print(sum(len(w.translate(None, letters)) == len(w) for line in f for w in line.split()))

如果尝试删除任何letters后该单词的长度相同,则该单词不包含字母中的任何字母。

或使用any

with open("in.txt", 'r') as f:
    letters = raw_input("Enter the key you want to exclude")
    print(sum(not any(let in w for let in letters) for line in f for w in line.split()))

any(let in w for let in letters)将检查字母中的每个字母,看每个单词中是否有字母,如果找到一个禁止的字母,它将短路并返回True ,否则,如果单词中没有字母,则返回False然后继续下一个词。

除非每行只有一个单词,否则您不能使用if l in word ,您需要将其拆分为单个单词。

使用您自己的代码,当您在单词中找到字母时,您只需要中断即可;否则,如果我们遍历所有字母但未找到匹配项,请打印该单词:

for line in fin:
    word = line.strip()
    for l in letters:
        if l  in word:
            break 
    else:
         print word

在循环中执行所需操作的pythonic方法是使用any:

for line in fin:
    word = line.strip()
    if not any(l not in word for l in letters): 
         print word

这等效于break / else好得多。

如果您想要总和,则需要随时进行跟踪:

  total = 0
  for line in fin:
      word = line.strip()
      if not any(l not in word  for l in letters): 
           total += 1
 print(total)

这是一种效率较低的方法:

print(sum(not any(let in w.rstrip() for let in letters) for word in f))

只是另一种方式。

exclude = set(raw_input("Enter the key you want to exclude"))
with open("demo.txt") as f:
    print len(filter(exclude.isdisjoint, f.read().split()))

这个更好:

    forbidden='ab'
    listofstring=['a','ab','acc','aaabb']
    for i in listofstring:
        if not any((c in i) for c in forbidden):
            print i

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM