Python中统计文本字数

        

# 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的异常捕获。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值