如何读取然后用split解析并写入文本文件?

2024-10-04 11:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力让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

我从文本文件中读取的示例。你知道吗

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

我离真正有效地抓取这些数据还差得很远,但我正在尝试一个开始。你知道吗

我的目标是只提取类名和编号并删除描述。你知道吗

一如既往地谢谢你!你知道吗


Tags: 数据outputreadlinelineopen协同工作建模学生
2条回答

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

接下来,我假设每个文本块都包含信息“XX小时讲座”,顺序相同,其中“XX”表示任何类型的数字(时间范围)。在变量“match\u re”中,我定义了一个正则匹配表达式,只与定义的点“XX”匹配。通过使用匹配.组(2) “我把我的匹配限制在最里面的括号里。你知道吗

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

下面我提取字符串:WELD 190 Manufacturing I Introduction to MasterCAM(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")

我相信要解决当前的问题,如果您只尝试解析一行,那么只需将第二行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 Manufacturing I Introduction to MasterCAM (3

相关问题 更多 >