代码之家  ›  专栏  ›  技术社区  ›  Luís Martins

读取行,直到找到特定字符

  •  1
  • Luís Martins  · 技术社区  · 7 年前

    我正在尝试读取一个文件(读取文件中的每一行,包括字母、数字和字符)。脚本通常需要工作,文件将类似,但有一些更改。

    现在,当它找到这样一行代码时,它会读到:“**HWCOLOR COMP 1066 30”。我需要脚本读取所有行,直到找到“**HW”。下面的脚本用于解释第一个问题。

    如何编写脚本来读取文件,直到找到“**HW”并停止?

    我试图用**HW”替换“**HWCOLOR COMP 1066 30”,但它不起作用,因为所有字符都不匹配。

    data = [] 
    
    with open('valvebody_nodes_rec.txt') as f:
        # Skips text before the beginning of the interesting block:
        for line in f:
            if line.strip() == '*NODE, SYSTEM=R':
                break    
    
        # Reads text until the end of the block:
        for line in f:
            if line.strip() == '**HWCOLOR COMP       1066    30':
                break
            data.append([x.strip() for x in line.split(',')])   #intersect text
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   ErikusMaximus    7 年前

    我建议使用正则表达式而不是字符串匹配。 https://docs.python.org/3/library/re.html

    match = re.search('your regex here', line)
    if match:
        ...
    

    如果您不熟悉正则表达式,请查找教程,了解基本知识后再进行一些 Regex Golf 。正则表达式非常强大和有用,因此我强烈建议学习它们。

    或者,您也可以执行以下操作

    if line.strip().startswith('**HW'):
    

    if '**HW' in line: