简体   繁体   English

尝试使用正则表达式删除行并写入新文件时出错

[英]Error when trying to remove lines using regex and write to new file

I have a text file where each line starts with a '0', followed by a tab, and then ideally some text - however, some lines just have a '0' followed by whitespace, and I need to remove those.我有一个文本文件,其中每一行都以“0”开头,然后是制表符,然后最好是一些文本 - 但是,有些行只有一个“0”,后跟空格,我需要删除它们。

EDIT: I added 'w' to the second file path, as recommended below, but now I get the following error message:编辑:我按照下面的建议将“w”添加到第二个文件路径,但现在我收到以下错误消息:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ed7474583899> in <module>
      3     with open('test_02.txt', 'w', ) as append_file:
      4         for line in file:
----> 5             if not pattern(line):
      6                 append_file.write(" "+r)
      7         append_file.write("\n")

TypeError: 're.Pattern' object is not callable

when I run this code当我运行此代码时

import re

pattern = re.compile("^0\s+$")
with open('test.txt', 'w') as file:
    with open('test_02.txt') as append_file:
        for line in file:
            if not pattern(line):
                append_file.write(" "+r)
        append_file.write("\n")

but when I run it I get the following error message但是当我运行它时,我收到以下错误消息

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-26-41d28ce0cbdf> in <module>
      3 pattern = re.compile("^0\s+$")
      4 with open('test.txt') as file:
----> 5     with open('test_02.txt') as append_file:
      6         for line in file:
      7             if not pattern(line):

FileNotFoundError: [Errno 2] No such file or directory: 'test_02.txt'

I've used the same 'with open' command before to remove stop words from the text and save them to a new file, so I'm not sure why it's generating that error now, and I haven't had any luck troubleshooting.我之前使用过相同的“with open”命令从文本中删除停用词并将它们保存到一个新文件中,所以我不确定为什么它现在会产生该错误,而且我没有任何运气故障排除。

  1. open the file as writeable if you plan to write to that file: with open( 'name', 'w') as fout etc.如果您打算写入该文件,请将文件打开为可写: with open( 'name', 'w') as fout等。
  2. you cannot call compiled re pattern pattern(line) , you have to use pattern.match(line) or something like that.你不能调用编译re模式pattern(line) ,你必须使用pattern.match(line)或类似的东西。
  3. when creating re pattern, it's usually a good idea to use r'...' string as a pattern.创建re模式时,使用r'...'字符串作为模式通常是个好主意。
  4. append_file.write(" "+r) is an error, since r is not defined anywhere. append_file.write(" "+r)是一个错误,因为r没有在任何地方定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM