我有一个文本文件,其结果如下:
欢迎使用您的结果
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!")
答案 0 :(得分:0)
从我对这个问题的理解,一个简单的正则表达式匹配将解决问题。你可以这样做:
逐行读取文件。 像这样制作一个正则表达式模式,从字符串中获取数据:
[0, i]
假设文件中的一行是否存储在变量result中:
>>> pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"
导入>>> result = "The result of 25+50=75"
库并使用匹配函数,如下所示,它为您提供字符串中的数据:
re
>>> s = re.match(pattern, result)
>>> print s.groups()
然后,您可以从此元组中获取数字并使用它进行任何操作。更改正则表达式以满足您的需要,但在开始时给出文件的内容,这应该没问题。