如何读取然后解析拆分并写入文本文件?



我正在努力让readline((和split((像我期望的那样一起工作。我试图使用 .split('('( 从文本文件中剪切一些数据并将其中一些数据写入下一个文本文件。

我试过从行中写出所有内容。 我已经尝试了 [cnt % 2] 来获得我期望的。

line = fp.readline()
fw = open('output.txt', "w+")
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = fp.readline()
line = line.split(')')[0]
fw.write(line + "n")
cnt += 1

从文本文件中读取的示例。

WELD 190 制造 I 大师CAM简介 (3( 11/2小时讲座 - 41/2小时实验室 注意:交叉列为DT 190/ENGR 190/IT 190 本课程将向学生介绍MasterCAM和2D以及基本的3D 建 模。学生将收到需要的零件的说明和图纸 2 轴或 3 轴加工。学生将设计,建模,编程,设置和运行 它们在各种机器上的零件,包括等离子切割机、水射流切割机和 铣床。 WELD 197 焊接技术主题 (.5 - 3(

我离真正有效地抓取这些数据还很远,但我正在尝试开始。

我的目标是仅提取类名和编号并删除描述。

一如既往地感谢!

我相信要解决您当前的问题,如果您只尝试解析一行,您只需要将第二行line = fp.readline()移动到 while 循环的末尾。目前,您实际上是从第二行开始分析,因为您已经在示例代码的第一行中使用了readline

更改后,它将如下所示:

line = fp.readline() # read in the first line
fw = open('output.txt', "w+")
cnt = 1
while line:
print("Line {}: {}".format(cnt, line.strip()))
line = line.split(')')[0]
fw.write(line + "n")
cnt += 1
line = fp.readline() # read in next line after parsing done

示例输入文本的输出:

WELD 190 制造 I MasterCAM 简介 (3

假设您的其他类文本块与您显示的结构相同,您可能希望使用正则表达式来提取类名和类号:

接下来,我假设每个文本块都包含信息"XX小时讲座",其顺序与"XX"代表任何类型的数字(时间范围(相同。在变量"match_re"中,我定义了一个正则匹配表达式,使其仅与定义的点"XX小时讲座"匹配。通过使用 'match.group(2(' 我将我的匹配限制在最内侧的括号对中的部分。

下面的匹配表达式对您来说可能还不完整,因为我不知道您的整个文本文件。

下面我提取字符串:WELD 190 制造 I 大师CAM简介 (3(

import re
string = "WELD 190 Manufacturing I Introduction to MasterCAM (3) 1½ hours lecture - 4½ hours laboratory Note: Cross listed as DT 190/ENGR 190/IT 190 This course will introduce the students to MasterCAM and 2D and basic 3D modeling. Students will receive instructions and drawings of parts requiring 2- or 3-axis machining. Students will design, model, program, set-up and run their parts on various machines, including plasma cutters, water jet cutters and milling machines. WELD 197 Welding Technology Topics (.5 - 3)"
match_re = "(^(.*)d.* hours lecture)"
match = re.search(match_re,string)
if match:
print(match.group(2))
else:
print("No match")

最新更新