2016-12-01 97 views
0

我希望能收到一些关于我在Python 3中编写的代码的一些反馈 - 我试图编写一个程序来读取其中包含页码的输入文件。页码格式为:“[13]”(这意味着你在第13页)。我的代码现在的问题是:查找并从行中删除特定的字符串

pattern='\[\d\]' 

for line in f: 
if pattern in line: 
    re.sub('\[\d\]',' ') 
    re.compile(line) 
    output.write(line.replace('\[\d\]', '')) 

我也曾尝试:

​​

当我运行这些程序,一个空白文件被创建,而不是包含原始文本减去页码的文件。提前感谢您的任何建议!

回答

1

你的if语句不起作用,因为没有进行正则表达式匹配,它正在寻找\[\d\]的文字字符串line

for line in f: 
    # determine if the pattern is found in the line 
    if re.match(r'\[\d\]', line): 
     subbed_line = re.sub(r'\[\d\]',' ') 
     output_file.writeline(subbed_line) 

此外,您错误地使用了re.compile()。它的目的是将你的模式预编译成一个函数。如果您使用该模式的次数会提高性能,因为您只评估一次表达式,而不是每次循环时重新评估一次。

pattern = re.compile(r'\[\d\]') 

if pattern.match(line): 
    # ... 

最后,你是因为你使用output_file.write()其中将一个字符串作为整个文件得到一个空白文件。相反,您希望使用output_file.writeline()将行写入文件。

0

您不会将未修改的行写入输出。

尝试这样的事情

if pattern in line: 
    #remove page number stuff 
output_file.write(line) # note that it's not part of the if block above 

这就是为什么你的输出文件是空的。

相关问题