【发布时间】:2023-11-30 12:24:01
【问题描述】:
我有一个文本文件,其结果如下所示:
欢迎您的结果
50+25=75的结果
60+25=85的结果
70+25=95的结果
80+25=105的结果
我需要 python 来读取文件并提取“=”左侧的数字并将它们相加。我不知道如何让它工作。
# take input from the user
print("Select operation.")
print("1.Display The Content of the result file")
print("2.Add two numbers")
print("3.Subtract two numbers")
print("4.Multiply two numbers")
print("5.Divide two numbers")
print("6.Append results to file")
print("7.Display Total of inputs")
print("8.Display Average of inputs")
print("9.Exit")
choice = input("Select an option(1-9):")
if choice == 1:
file = open('results.txt', 'r')
print file.read()
elif choice >= 2 and choice <= 5:
l_range = int(input("Enter your Lower range: "))
h_range = int(input("Enter your Higher range: "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < l_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
elif num2 > h_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
else:
if choice == 2:
print "The result of", num1,"+", num2,"=", add(num1,num2)
resultstr = "The result of " + str(num1) + "+" + str(num2) + "=" + str(add(num1,num2))
elif choice == 3:
print "The result of", num1,"-",num2,"=", subtract(num1,num2)
resultstr = "The result of " + str(num1) + "-" + str(num2) + "=" + str(subtract(num1,num2))
elif choice == 4:
print "The result of", num1,"*", num2,"=", multiply(num1,num2)
resultstr = "The result of " + str(num1) + "*" + str(num2) + "=" + str(multiply(num1,num2))
elif choice == 5:
print "The result of", num1,"/", num2, "=", divide(num1,num2)
resultstr = "The result of " + str(num1) + "/" + str(num2) + "=" + str(divide(num1,num2))
if num2 == 0:
print "The result of", num1,"/", num2, "=", "You can't divide by zero!"
elif choice == 6:
print("The results have been appended to the file")
file = open('results.txt', 'a')
file.write(resultstr + "\n")
file.close()
elif choice == 7:
print ("Display total inputs")
elif choice == 8:
print ("Display average of total inputs")
elif choice == 9:
print ("Goodbye!")
else:
print("Invalid input")
lp_input = raw_input("Do you want to perform another action? Y/N:")
if lp_input == 'n':
print("Goodbye!")
【问题讨论】:
-
都是加法和正数吗?
-
我投票结束这个问题,因为这既不是代码编写也不是教程服务
-
这是一个简单的任务。你试过什么?
-
我意识到这可能是一项简单的任务,但不是将字符串拆分然后使用它们。
-
@jonrsharpe 如果您愿意,我们可以关闭它。我在多个 vba 论坛上,并定期协助新的 vba 用户。我已经编写了 90% 的应用程序,但不知道这部分从哪里开始。我已经阅读了多个关于从文件中读取/拆分文本的教程,但不知道如何组合该过程。
标签: python file text calculator