【问题标题】:python, search .txt file and inject characterpython,搜索.txt文件并注入字符
【发布时间】:2015-04-26 20:10:43
【问题描述】:

对于我事先不知道 python 如何处理字符串,我深表歉意。我有一个至少 1000 行长的 .txt 文件。如下所示

:dodge
1 6 some description string of unknown length
E7 8 another description string 
3445 0 oil temp something description voltage over limit etc

:ford
AF 4 description of stuff
0 8 string descritiopn

我想要做的基本上是放一个“;”在每个字符串之前,所以我最终会得到如下

:dodge
1 6 ;some description string of unknown length
E7 8 ;another description string 
3445 0 ;oil temp something description voltage over limit etc

:ford
AF 4 ;description of stuff
0 8 ;string descritiopn

我的想法是打开文件,搜索“:”字符,下一行,转到“”字符,转到下一个“”字符并写一个“;”。另一个想法是转到文本文件中的“/n”字符如果下一个字符!=“:”然后寻找第二个空格 导入系统 导入文件输入

with open("testDTC.txt", "r+") as f:
for line in f:
    if ' ' in line:     #read first space
        if ' ' in line:     #read second space
            line.append(';')

    f.write(line)

f.close()

我知道它离我需要的东西还很远,但是自从我在 python 中进行字符串操作以来已经很长时间了。

【问题讨论】:

  • 您从哪里得知if 语句是从文件中读取的?
  • @Two-BitAlchemist 您从哪里得知 if 语句正在从文件中读取? if 语句正在测试一个字符串。您的评论对 OP 并不是特别有用。只是刻薄。
  • 在你想附加的字符串后面加上 ;曾经从数字本身开始吗?
  • 看看模式,我会选择稍微不同的逻辑。我会去插入一个 ;你第一次在每一行中看到一个小写字母不是以 : 开头的(行用 \n 分隔)
  • @moorej 哦,我不知道。从 if 语句旁边的原始代码中的 cmets 说“读取 x 空间”?无论如何,应该还有更多,但我被叫走了。

标签: python string search text


【解决方案1】:

由于您只有 1000 行左右,我认为您可以使用 readlines() 一次读取所有内容并为每一行使用拆分。如果该行只有一个元素,则打印它,然后调用另一个循环,该循环处理具有多个元素的后续行,并用分号和元素的串联替换第三个 [2] 元素。然后你必须做一些事情来很好地输出这条线(这里是加入,但还有很多其他的解决方案),这取决于你想要什么。

with open('testDTC.txt') as fp:
    lines = fp.readlines()

for i in xrange(len(lines)):
    if len(lines[i].split()) == 1:
        print lines[i][:-1]
        i += 1
        while len(lines[i].split()) > 0:
            spl = lines[i].split()
            spl[2] = ";"+spl[2]
            print " ".join(spl)
            i += 1
            if i == len(lines):
                break
        print

【讨论】:

    【解决方案2】:

    您只需要在空白处拆分两次并加入字符串,对于简单的重复模式,您不需要正则表达式:

    with open("testDTC.txt") as f:
        for line in f:
            if line.strip() and not line.startswith(":"):
                spl = line.split(None,2)
                print("{} ;{}".format(" ".join(spl[:2]),spl[2]))
    

    要将更改写入原始文件,您可以使用fileinput.input 和inplace=True:

    from fileinput import input
    for line in input("testDTC.txt",inplace=True):
        if line.strip() and not line.startswith(":"):
            spl = line.split(None,2)
            print("{} ;{}".format(" ".join(spl[:2]),spl[2]),end="")
        else:
            print(line,end="")
    

    我们可以解包而不是索引:

            a, b, c = line.split(None,2)
            print("{} {} ;{}".format(a, b, c),end="")
    

    输出:

    :dodge
    1 6 ;some description string of unknown length
    E7 8 ;another description string 
    3445 0 ;oil temp something description voltage over limit etc
    
    :ford
    AF 4 ;description of stuff
    0 8 ;string descritiopn
    

    对于 python 2,您可以删除 end="" 并在 print 语句后使用逗号,即 print(line),

    我们避免使用line.startswith(":") 开头的段落行和if line.strip() 的空行。

    【讨论】:

    • “简单的重复模式不需要正则表达式”是完全正确的。
    • 我应该为任何其他寻找类似问题的人补充,即 python 2.x 和 3.x 之间的打印处理方式不同......以上在 3.x 上运行良好,但“打印”行为在 2.x 中有所不同,并且不会识别 end=""
    【解决方案3】:

    您可以使用非常简单的算法来完成此操作,而无需调用正则表达式,这样您就可以看到发生了什么。

    with open('test.txt') as infile:
        with open('out.txt', 'w') as outfile:
            for line in infile:
                if not line or line.startswith(':'):   # Blank or : line
                    outfile.write(line or '\n')        # pass it through
                else:
                    line_parts = line.split(None, 2)   # split at most twice
                    try:
                        # try adding the semicolon after the 2nd space
                        line_parts[2] = ';' + line_parts[2]
                    except IndexError:
                        pass
                    outfile.write(' '.join(line_parts))
    

    如果你真的想一次读取一个文件中的字符,你最终会使用read 方法和seek,但这在 Python 中是不必要的,因为你有像文件迭代和强大的字符串方法来帮助你。

    【讨论】:

      【解决方案4】:

      这就是我会做的:

      for line in f:
          if ' ' in line:
              sp = line.split(' ', 2)
              line = '%s %s ;%s' % (sp[0], sp[1], sp[2])
      

      【讨论】:

        【解决方案5】:

        根据您的示例,您的第二列中似乎有一个或多个用空格分隔的数字,例如8, 6 后面是第三列中的一些描述,似乎没有任何数字。如果是一般情况,不只是本例,你可以利用这个事实来搜索由空格分隔的数字,并在其后添加;,如下所示:

        重新导入

        rep = re.compile(r'(\s\d+\s)')    
        
        out_lines = []
        
        with open("file.txt", "r+") as f:
            for line in f:      
                re_match = rep.search(line)
                if re_match:
                    # append ; after the found expression.                         
                    line = line.replace(re_match.group(1), re_match.group(1)+';')        
                out_lines.append(line)
        
        
        
        with open('file2.txt', 'w') as f:
            f.writelines(out_lines)
        

        得到的file2.txt如下:

        :dodge
        1 6 ;some description string of unknown length
        E7 8 ;another description string
        3445 0 ;oil temp something description voltage over limit etc
        
        :ford
        AF 4 ;description of stuff
        0 8 ;string descritiopn
        

        【讨论】:

          猜你喜欢
          • 2011-09-07
          • 2021-10-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-15
          • 1970-01-01
          相关资源
          最近更新 更多