我有一个关于文本数据集特征提取的查询。使用来自的预处理数据集
预处理后的数据是每个文档一行,每行的格式为:
feature:<count> .... feature:<count> #label#:<label>
假设我们有两条线:
<line 1> alpha: 3 beta:2 gamma: 1 delta: 0 echo:0 #label:1
<line 2> alpha: 0 foxtrot:0 mike: 0 beta: 1 delta:1 #label:0
所以我想提取这样的特征,我得到:
输出
到目前为止,我已经写了这个代码,但无法继续:
import pandas as pd
dict={}
total=pd.DataFrame()
with open ('amazon_book.review', 'r') as data:
for i in range(3):
line=data.readline()
for word in line.split():
key,value=word.split(sep=":")
dict[key]=value
请使用正则表达式。希望下面的代码能有所帮助。在数据帧总数中,您将获得所有功能和标签
import pandas as pd
import re
list_of_dict = []
str_feature_pattern = re.compile(r'(w+s*:s+d+)+')
str_label_pattern = re.compile(r'.*#(w+:d+)')
with open ('amazon_book.review', 'r') as data:
for i in range(3):
line=data.readline()
feature_match = str_feature_pattern.findall(line)
label_match = str_label_pattern.findall(line)
dict = {}
for f in feature_match:
vals = f.split(sep=":")
dict[vals[0]] = vals[1]
label_val = label_match[0].split(sep=':')
dict[label_val[0]] = label_val[1]
list_of_dict.append(dict)
total=pd.DataFrame(list_of_dict)