Python 基本计算方法和文件读取的应用

一、环境

Windows10、Python 3.6.5、anaconda、spyder

二、应用及操作

以下有三个应用列举,分别为A、B、C。
A. 编程实现一个命令窗程序,使得:
输入“A”则在屏上回显“Your input is A”
输入“我”则在屏上回显“Your input is 我”
等等。
输入ByeBye则退出程序.
代码:

while (True):
    str1=input("Please input a character:")
    if str1=="byebye":
        print("The Program will exit!")
        break;
    print("Your input is "+str1)

结果:
这里写图片描述
B
编程实现一个命令窗程序,使得:
* 输入“A”则在屏上回显A字符的ASCII码。
* 输入“4”则在屏上回显4字符的ASCII码。
* 输入“我”则在屏上回显“我”字的汉字内码。
……
* 输入ByeBye则退出程序。
代码:

while (True):
    str1=input("Please input a character:")
    if str1=="byebye":
        print("The Program will exit!")
        break;
    print("\""+str1+"\"的ASCII码为:"+str(ord(str1)))#str统一输出类型

结果:
这里写图片描述

C
编程实现一个命令窗程序,使得:
* 输入“你”翻译成英文“you”。
* 输入“书”翻译成英文“book”。
* 输入“中”翻译成英文“middle”。
* 输入“中国”翻译成英文“China”。
……
* 输入词典上没有的词则在屏上回显“查不到该词”。
* 输入ByeBye则退出程序.
这里我们需要用记事本做一个单词字典文件(.txt文件),作为一个文本文件读入,其中格式为:
<中文字词><对应英文>
如:字典文件 dictionary.txt内容是
<我>< I >
<你>< you >
<中国>< China >
……

单词字典文件如下:
这里写图片描述
代码:

# 打开一个文件并把内容放在数组中
dictionary=[]
with open("dictionary.txt","r") as f:
    dictionary=f.readlines();
    # 关闭文件并释放系统的资源
    f.close()

# 查找函数
def findword(content):
    chinese_content=""
    english_content=""  
    flag=0
    for dic_list in dictionary:
        # 把“<”和">"作为分隔符对字符串进行切片
        chinese_content=dic_list.split("<")[1].split(">")[0]
        english_content=dic_list.split(">")[1].split("<")[1]
        if content==chinese_content:
            flag=1
            return english_content
    if flag==0:
        english_content="查询无果"
    return english_content
# 循环操作
while (True):
    str1=input("请输入中文:")
    if str1=="byebye":
        print("退出程序!")
        break;
    print(findword(str1))   

结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/Yangchenju/article/details/81509926
今日推荐