# 打开文件
a = input("请输入文件路径:")
# D:/学习/Crypto/test.txt(左手正斜杠)
# D:\学习\Crypto\test.txt(右手反斜杠)
# with open(r'D:/学习/Crypto/test.txt', mode='r') as f:
with open(a, mode='r') as f:
b = f.read() # 读文件并自动关闭
c = b.lower() # 转小写
# 统计单词
dict = {}
keys = c.split() # 字典的键
print(keys)
for key in keys: # 遍历列表
if key in dict.keys(): # 值在字典中,加1
dict[key] += 1 # dict[key] = dict[key]+1
else:
dict[key] = 1 # 值不在字典中,加入字典,value为1
# 字典元素的添加,字典名[键]=值
for word, count in dict.items():
print(f'{word}: {count} 次')
# 法二:
# 调用函数
import string
def count_words(file_path):
# 打开文件并读取内容
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# 去除标点符号并转为小写
content = content.translate(str.maketrans('', '', string.punctuation))
content = content.lower()
# 拆分单词
words = content.split()
# 统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
# 用你的文件路径替换 'your_file.txt'
file_path = input('your_file.txt:')
result = count_words(file_path)
# 打印结果
for word, count in result.items():
print(f'{word}: {count} 次')
若用close()方法关闭文件:
file = open(file_path, mode='', encoding='')
# 对文件操作
file.close()
写正常路径时要注意转义,\t会被识别成横向制表符,因此要在前面加一个'\',或在整个'路径'前加r(或R)使其成为原始字符串。
试了下,正斜杠路径无需转义b( ̄▽ ̄)d,正斜杠路径多用于Linux系统中。
# 打开文件
# a = input("请输入文件路径:")
# D:/学习/Crypto/test.txt(左手正斜杠)
# D:\学习\Crypto\test.txt(右手反斜杠)
# with open('D:/学习/Crypto/test.txt', mode='r') as f:
f = open('D:\学习\Crypto\\test.txt', mode='r')
b = f.read()
c = b.lower() # 转小写
f.close()
# 统计单词
dict = {}
keys = c.split() # 字典的键
print(keys)
for key in keys: # 遍历列表
if key in dict.keys(): # 值在字典中,加1
dict[key] += 1 # dict[key] = dict[key]+1
else:
dict[key] = 1 # 值不在字典中,加入字典,value为1
# 字典元素的添加,字典名[键]=值
for word, count in dict.items():
print(f'{word}: {count} 次')
money = 5000000
name = None
name = input("你的姓名:")
def inquire(show_header):
if show_header:
print("----------查询----------")
print(f"{name},您好,您的余额为:{money}元")
def deposit(num):
global money
money += num
print("----------存款----------")
print(f"{name},您好,您的存款金额为:{num}元")
inquire(False)
def withdrawal(num):
global money
money -= num
print("----------取款----------")
print(f"{name},您好,您的取款金额为:{num}元")
inquire(False)
def main():
print("---------主菜单---------")
print(f"{name},您好,欢迎来到黑马银行ATM,请选择您需要进行的操作:")
print("查询余额 \t\t【输入1】")
print("存款\t\t\t【输入2】")
print("取款\t\t\t【输入3】")
print("退出\t\t\t【输入4】")
return input("请输入您的选择")
while True: #循环
keyboard_input = main()
if keyboard_input == "1":
inquire(True)
continue
elif keyboard_input == "2":
num = int(input(f"{name},请输入您的存款金额:"))
deposit(num)
continue
elif keyboard_input == "3":
num = int(input(f"{name},请输入您的取款金额:"))
withdrawal(num)
continue
else:
print("程序已退出")
break