【问题标题】:Parse raw text data and extract a particular value in Python解析原始文本数据并在 Python 中提取特定值
【发布时间】:2020-03-13 00:03:49
【问题描述】:

我的数据库中的一列以下面提到的格式存储文本信息。文本不是标准格式,有时“保险日期”字段之前可能会有额外的文本。当我在 Python 中进行拆分时,它可能会将这个“保险日期”放在不同的列中。在这种情况下,我需要在所有列中搜索“保险日期”值。

示例文本

"Accumulation Period - period of time insured must incur eligible medical expenses at least equal to the deductible amount in order to establish a benefit period under a major medical expense or comprehensive medical expense policy.\n
Insurance Date 12/17/2018\n
Insurance Number 235845\n
Carrier Name SKGP\n
Coverage $240000"

预期结果

INS_NO     Insurance Date     Carrier Name
235845    12/17/2018          SKGP   

我们如何解析这样的原始文本信息并提取保险日期的值

我正在使用下面的逻辑来提取它,但我不知道如何将日期提取到另一列中

df= pd.read_sql(query, conn)
df2=df["NOTES"].str.split("\n", expand=True)

【问题讨论】:

  • 如果一直是这种格式,使用正则表达式可能更容易。
  • 我不知道如何将日期提取到另一列中 你能更具体一点吗?请提供minimal reproducible example

标签: python python-3.x parsing text


【解决方案1】:

使用正则表达式

如果文本遵循某种模式(或多或少),您可以使用regex.
请参阅 python 文档了解正则表达式操作here

示例

查看并尝试两种可能解决方案的代码here
您可以在下面找到一个简化的示例。

text = """
Accumulation Period - period of time insured must incur eligible medical expenses at least equal to the deductible amount in order to establish a benefit period under a major medical expense or comprehensive medical expense policy.
Insurance Date 12/17/2018
Insurance Number 235845
Carrier Name SKGP
Coverage $240000
"""

pattern = re.compile(r"Insurance Date (.*)\nInsurance Number (.*)\nCarrier Name (.*)\n")

match = pattern.search(text)

print("Found:")
if match:
    for g in match.groups():
        print(g)

输出

Found:
12/17/2018
235845
SKGP

【讨论】:

    【解决方案2】:

    如果我对您的理解正确,这可能会让您接近您所需要的:

    insurance = """
    "Accumulation Period - period of time insured must incur eligible medical expenses at least equal to the deductible amount in order to establish a benefit period under a major medical expense or comprehensive medical expense policy.\n
    Insurance Date 12/17/2018\n
    Insurance Number 235845\n
    Carrier Name SKGP\n
    Coverage $240000"
    """
    
    items = insurance.split('\n')
    filtered_items = list(filter(lambda x: x != "", items))
    del filtered_items[0]
    del filtered_items[-1]
    row = []
    for item in filtered_items:
        row.append(item.split(' ')[-1])
    
    columns = ["INS_NO ", "Insurance Date", "Carrier Name"]      
    df = pd.DataFrame([row],columns=columns)
    df
    

    输出:

        INS_NO  Insurance Date  Carrier Name
    0   12/17/2018  235845     SKGP
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2013-05-22
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多