最简单的方法是把字母组成一个集合,把每一行分成单词,然后总结有多少次没有禁止字母的单词:
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))