首页 > 解决方案 > 如何访问 re.findinter 输出对象中的数据?

问题描述

我想从我用 regex.findinter 生成的对象中访问“跨度”和“匹配”数据。但是我找不到如何将对象结构转换为 pandas df 以便我可以更轻松地操作它。

我可以遍历对象以打印数据。但是 regex.findinter 文档没有说明如何访问数据。我能找到的最好的是页面https://docs.python.org/2.0/lib/match-objects.html

我尝试将行附加到熊猫 df 但没有运气。见代码。它给出错误:TypeError:无法连接类型为“”的对象;只有 pd.Series、pd.DataFrame 和 pd.Panel(已弃用)obj 有效

import re
import pandas as pd


def find_rez(string):
    regex = re.compile(r'\s\d{10}\s')
    return(regex.finditer(string))

#open file with text data
file = open('prepaid_transactions_test2.txt')
text = file.read()

#get regex object with locations of all matches.
rez_mo = find_rez(text)

#Create empty df with span and match columns.
df = pd.DataFrame(columns=['span','match'])

#Append each row from object to pandas df. NOT WORKING.
for i in rez_mo:
    df.append(i)

我想要一个以范围和匹配作为列的 pandas df。但我无法转换它看起来的类型。

标签: pythonregex

解决方案


我刚刚找到了解决方案。可能不是最优雅的,但....它有效。

for i in rez_mo:
    df.loc[len(df)]=[i.start()],[i.group()]

推荐阅读