我有一个这样的文本文件:
This is just
an example of
a textfile
并希望找到不包含" e"的所有单词的总和。这个总和是为每一行打印的,应该是该行中单词的总和。
目前我有这个:
with open(sys.argv[1], "r") as f:
count = 0
for line in f:
words = line.split()
for word in words:
if "e" not in word:
for char in word:
count += 1
print(count)
我得到的输出是:
4
6
10
12
14
15
应该是:
10
4
1
答案 0 :(得分:0)
您可以使用import ....
import ....
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
# more code here...
# more code here...
内置来获取字符串的长度。您获得的数字大于预期的原因是您没有为每一行重置len
变量,而且还要在每个单词之后打印,而不是每行都打印。
count
你可以更紧凑地写这个
with open(sys.argv[1], "r") as f:
for line in f:
count = 0
words = line.split()
for word in words:
if "e" not in word:
count += len(word)
print(count)