【发布时间】:2018-08-06 16:11:53
【问题描述】:
使用 Python 3.6 读取文本文件以提取 relative 行以转换为 pandas 数据帧。
工作原理:在文本文档中搜索短语并将该行转换为 pandas df。
import pandas as pd
df = pd.DataFrame()
list1 = []
list2 = []
with open('myfile.txt') as f:
for lineno, line in enumerate(f, 1):
if 'Project:' in line:
line = line.strip('\n')
list1.append(repr(line))
# Convert list1 into a df column
df = pd.DataFrame({'Project_Name':list1})
什么不起作用:根据搜索结果返回相对行。在我的情况下,我需要将“相对”行 -6 到 -2(在本文前面)存储为 Pandas 列。
with open('myfile.txt') as f:
for lineno, line in enumerate(f, 1):
if 'Project:' in line:
list2.append(repr(line)-6) #<--- can't use math here
返回:TypeError:不支持的操作数类型 -: 'str' 和 'int'
还尝试使用部分成功的范围:
with open('myfile.txt') as f:
for lineno, line in enumerate(f, 1):
if 'Project' in line:
all_lines = f.readlines()
required_lines = [all_lines[i] for i in range(lineno-6,lineno-2)]
print (required_lines)
list2.append(required_lines) #<-- does not work
Python 将打印前 4 行目标行,但它似乎无法将其保存为列表或循环遍历文本文档中“项目”的每个发现。有没有更好的方法来保存搜索词上方(或下方)的相对行的结果?非常感谢。
文本数据如下:
0 Exhibit 3
1 Date: February 2018
2 Description
3 Description
4 Description
5 2015
6 2016
7 2017
8 2018
9 $100.50 <---- Add these as different dataframe columns
10 $120.33 <----
11 $135.88 <----
12 $140.22 <----
13 Project A
14
15 Exhibit 4
16 Date: February 2018
17 Description
18 Description
19 2015
20 2016
21 2017
22 2018
23 $899.25 <----
24 $901.00 <----
25 $923.43 <----
26 $1002.02 <----
27 Project B
【问题讨论】:
-
如果您可以发布您的输入数据的样子以及您希望输出的样子会有所帮助。
-
添加了文本的示例,感谢 Alex
标签: pandas search python-3.6