# Word Count
# with open('test.txt','r',encoding='utf-8') as file_path:
# content = file_path.read()
# number_list = content.split()
# result = len(number_list)
# print(number_list)
#
# # output the text word number
# print(f"the file has {result} words in total .")
#Word Count
with open("test.txt",'r',encoding='utf-8') as file:
content = file.read()
# # the first way
# characters = [char for char in content]
# result = len(characters)
# # the second way
# characters = ' '.join(content).split()
# result = len(characters)
# the third way
characters = list(content)
result = len(characters)
print(f"the text has {result} words .")
都是先创建一个文件,然后在读取。提供了三种方法:
利用for循环遍历文本;
先给文本字符间添加空白,利用split函数把字符串拆成一个个字符,返回一个列表,通过测量列表长度来统计字数;
直接使用list函数。
补充:
list_11 = list(range(1,10,2))
def square(x):
result = x * x
return result
new_list = map(square,list_11)
print(list(new_list))
#test the 'lambda' function
double = lambda x : x * 2
print(double(2))
这也是在遍历列表时常用的map,lambda函数
昨天没有写,昨天主要在学python的异常捕获。