python - 查找特定字符串的行并在该行之后读取文本文件
问题描述
我有一个文本文件(~20MB),我想从中提取一些信息。我感兴趣的信息如下所示:
Generate :
MESH : Cartesian
1.00000 0.00000 0.00000
0.00000 0.84680 0.00000
0.00000 0.00000 0.80724
MESH : 4 unique points
x y z Weight
1 0.000000 0.000000 0.000000 0.3906
2 0.125000 0.000000 0.000000 0.7812
3 0.250000 0.000000 0.000000 0.7812
4 0.375000 0.000000 0.000000 0.7812
我想在第二次出现字符串“MESH”后将 x、y、z 列保存到数组中。我尝试使用正则表达式,但我的解决方案将结果保存为列表,并且为了将来的目的调用这些值变得过于复杂。这是我的尝试:
import re
line_number = 0
mesh_list = []
Qp = []
with open('out.test','r') as f:
for line in f:
line_number +=1
if 'MESH' in line:
mesh_list.append([(line_number),line.rstrip()])
point_info = mesh_list[1]
output_line = point_info[0] ## Line number where MESH appears the second time.
point_list = point_info[1].split()
num_of_points = int(point_list[1]) ## Get number of unique points.
with open('out.test','r') as f:
for i, line in enumerate(f):
if output_line+1 <= i <= output_line+num_of_points:
Qp.append([line])
print(Qp)
在这一点上,'Qp' 拥有我需要的所有行,但是我怎样才能将 x、y、z 列从这个块中分离出来呢?使用熊猫会更容易吗?
解决方案
您可以使用pd.read_csv
自定义skiprows=
和sep=
参数:
import re
import pandas as pd
r = re.compile(r"MESH : \d+ unique points")
line_counter = 0
with open("your_file.txt", "r") as f_in:
for l in f_in:
line_counter += 1
if r.search(l):
break
df = pd.read_csv("your_file.txt", skiprows=line_counter, sep=r"\s+")
print(df)
印刷:
x y z Weight
1 0.000 0.0 0.0 0.3906
2 0.125 0.0 0.0 0.7812
3 0.250 0.0 0.0 0.7812
4 0.375 0.0 0.0 0.7812
推荐阅读
- svn - 使用命令行仅列出来自 SVN 的特定类型的文件
- spring-boot - neo4j docker 容器拒绝连接
- javascript - 尝试导致循环的 window.location 或 window.location.href 重定向
- bootstrap-4 - 更新 bootstrap-year-calendar 而不重新渲染整个日历?
- inno-setup - 将 RegQueryStringValue 与 Inno Setup 6.0.0 和 HKCU 一起使用。GetPathInstalled
- blockchain - 缺少 Multichain.conf - 如何创建
- macos - csproj 文件中的 .NET 核心输出类型
- java - 尝试移动到底部时,JPanel 被压缩并消失
- html - “public_html”自动出现在 URL 中的文件夹名称之后并导致 404
- php - Microsoft Translator API v3 - PHP 使用 cURL 代替 file_get_contents