def readFile(filename):
with open(filename, 'r') as file: # 只读模式打开文件
content = file.read() # 文件内容读入到一个字符串
return content # 返回字符串
def replaceTxt(txt):
for ch in '!"#$%&()*+,./:;<=>?@[\\]^_‘{|}~\n':
txt = txt.replace(ch, " ") # 将字符串中特殊字符替换为空格,注意要赋值回去
return txt.split() # 根据空格将字符串切分为列表返回
if __name__ == '__main__':
name = input() # 输入文件名
content = readFile(name) # 读文件,返回字符串
result = replaceTxt(content) # 字符串替换和切分
print(len(result)) # 输出列表长度
# def readFile(filename):
# txt = open(filename,'r').read()
# for ch in '!"#$%&()*+,./:;<=>?@[\\]^_‘{|}~\n':
# txt = txt.replace(ch, " ") #将文本中特殊字符替换为空格
# return txt
# name = input()
# lsWords = readFile(name).split()
# print(len(lsWords))
统计文本中单词数
最新推荐文章于 2024-04-18 14:45:16 发布