【问题标题】:Printing a single line in a multi-line string在多行字符串中打印单行
【发布时间】:2020-01-13 07:35:55
【问题描述】:

我设法使用 pytesseract 将发票图像转换为文本。

多行字符串如下所示:

Receipt No: 20191220.001
Date: 20 December 2019
Invoice amount: $400.00

我想提取发票号码,只是使用子字符串的号码(即:20191220.001)。我设法通过index = string.find('Receipt No: ') 获取起始索引,但是当我使用子字符串函数提取数字print(string[index:]) 时,我得到以下结果:

20191220.001
Date: 20 December 2019
Invoice amount: $400.00

但我只想提取第一行。发票编号并非仅定义为 12 个字符,可能或多或少取决于供应商。如何只提取发票编号?我这样做是为了使会计流程自动化。

【问题讨论】:

  • 如果您总是知道它的第一行,那么只需阅读第一行,然后在该行上执行 string.find()。
  • 这就是你找到开始索引的方式,我猜你需要的是结束索引。然后你可以按string[index1:index2] 切片。多想一点。
  • 这能回答你的问题吗? How do I read the first line of a string?

标签: python automation


【解决方案1】:

你可以使用split:

s = '''Receipt No: 20191220.001
Date: 20 December 2019
Invoice amount: $400.00'''

number = s.split('Receipt No: ')[1].split('\n')[0]
print(number)

输出:

20191220.001

或者如果你想使用find,你可以这样做:

index1 = s.find(':')
index2 = s.find('\n')
print(s[index1+1:index2].strip())

【讨论】:

    【解决方案2】:

    试试:

    import re
    s = """
    Receipt No: 20191220.001
    Date: 20 December 2019
    Invoice amount: $400.00"""
    p = re.compile("Receipt No\: (\d+.\d+)")
    result = p.search(s)
    index = result.group(1) #'20191220.001'
    

    【讨论】:

      【解决方案3】:

      用“\n”分隔列表中的字符串 您将获得由换行符分隔的字符串的每个部分作为列表元素。然后你可以参加你想要的部分

      string = """Receipt No: 20191220.001
      Date: 20 December 2019
      Invoice amount: $400.00"""
      
      your_list = string.split("\n")
      data = your_list[0]
      

      【讨论】:

        【解决方案4】:

        您可以尝试使用拆分功能。

        使用 open("filename",'r') 作为数据加载:

        for i in dataload.readlines():
        
            if "Receipt No:" in i:
        
                print(i.split(":")[1].strip())
        

        输出-

        20191220.001

        if "Receipt No:" in i: ---> 你可以根据你的要求改变 if "**" 参数

        【讨论】:

          【解决方案5】:

          如果你只关心第一行,你可以找到第一次出现的行结束符作为你的号码的结尾。请注意,您的号码的开头是子字符串的结尾(“收据号:”),而 find 函数返回子字符串的开头。

          string = '''Receipt No: 20191220.001
          Date: 20 December 2019
          Invoice amount: $400.00'''
          sub = 'Receipt No: '
          start = string.find(sub) + len(sub)
          end = string.find('\n')
          print(string[start:end])
          

          如果您还关心其他线路。您可以使用 split 并单独处理每一行。

          lines = string.split('\n')
          sub = 'Receipt No: '
          index = lines[0].find(sub) + len(sub)
          print(lines[0][index:])
          # Process line 1
          # Process line 2
          

          【讨论】:

            猜你喜欢
            • 2021-07-12
            • 2016-07-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-29
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多