【问题标题】:pulling numbers out of text从文本中提取数字
【发布时间】: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


【解决方案1】:

根据我对问题的理解,一个简单的正则表达式匹配就可以解决问题。你可以这样做:

逐行读取文件。 像这样制作一个正则表达式模式,以从字符串中获取数据:

&gt;&gt;&gt; pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"

如果文件中的一行存储在变量结果中:

&gt;&gt;&gt; result = "The result of 25+50=75"

导入 re 库并使用 match 函数,这样可以为您提供字符串中的数据:

&gt;&gt;&gt; s = re.match(pattern, result)

&gt;&gt;&gt; print s.groups()

('25', '50', '75')

然后您可以从此元组中获取数字并对其进行任何操作。更改正则表达式以满足您的需要,但考虑到文件开头的内容,这应该没问题。

【讨论】:

  • @kunalaggrarwal 我怎样才能得到与模式匹配的行?
  • file = open('results.txt', 'r') File.each_line('results.txt') do |li| puts li if (li["The result of (\d+?)[+-/*](\d+?)=(\d+).*"]) end
  • @ScottMorin s = re.match(pattern, result) 会给你None in s 如果该行不匹配。您可以在 if s: 之类的 if 语句中进行检查,只有当行匹配时才会如此。