1939年,Ernest Vincent Wright出版了一本名为 《Gadsby》 的小说,该小说里完全没有使用字符“e”。由于“e”是最常用的英文字符,因此这并不容易做到。
事实上,不使用这个最常用的符号(字符e)来构建一个孤立的想法是很难的。开始进展缓慢,但是经过有意识的、长时间的训练,你可以逐渐地熟练。
好啦,不再说题外话了(让我们开始编程练习)。
写一个叫做has_no_e的函数,如果给定的单词中不包含字符“e”,其返回 True 。
修改上一节中的程序,只打印不包含“e”的单词,并且计算列表中不含“e”单词的比例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| fin = open('words.txt')
def has_no_e(file_in):
count_ne = 0 #不含e的单词的个数
count = 0 #总单词个数
for line in file_in:
word = line.strip()
index = 0
while index < len(word):
if word[index] == 'e':
break
else:
index = index + 1
if index == len(word):
# print(word) #因为单词比较多,不一个个列出来了
count_ne = count_ne + 1
count = count + 1
print("不含e的单词有",count_ne,"个","单词一共有",count,"个","不含“e”单词的比例为",count_ne/count*100,"%")
has_no_e(fin)
|
上面是一个字母一个字母判断单词是不是包含‘e’的,下面是在 if 中使用 in 操作符简化后的方案:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| def has_no_e(word):
if 'e' not in word:
return True
else:
return False
fin = open('words.txt')
count = 0 #单词总数
count_ne = 0 #不含e的单词数
for line in fin:
word = line.strip()
count += 1
if has_no_e(word):
count_ne += 1
#print(word)
print("不含e的单词有",count_ne,"个","单词一共有",count,"个","不含“e”单词的比例为",count_ne/count*100,"%")
|
所得结果都是一样的:
不含e的单词有 37641 个 单词一共有 113809 个 不含“e”单词的比例为 33.07383423103621 %