【问题标题】:bug resulting from reading file读取文件导致的错误
【发布时间】:2016-03-02 20:27:29
【问题描述】:

我正面临一个相当难以捉摸的错误,这似乎是由从文件中读取引起的。 我已经简化了我的程序来演示这个问题:

考虑一下这个运行良好的程序:

import re

sourceString="Yesterday I had a pizza for lunch it was tasty\n";
sourceString+="today I am thinking about grabbing a burger and tomorrow it\n"; 
sourceString+="will probably be some fish if I am lucky\n\n\n";
sourceString+="see you later!"

jj=["pizza","steak","fish"]

for keyword in jj:
    regexPattern= keyword+".*";
    patternObject=re.compile(regexPattern,re.MULTILINE);
    match=patternObject.search(sourceString);
    if match:
        print("Match found for "+keyword)
        print(match.group()+"\n")
    else:
        print("warning: no match found for :"+ keyword+"\n")

我正在使用一个非常简单的正则表达式模式,但我从我的数组 jj 中获得了正则表达式的要点

脚本按预期工作(匹配包含“pizza”和“fish”但不匹配“steak”的模式)

现在在我的实际程序中,我试图从文件中读取这些关键字(我不想在源代码中硬编码)

到目前为止我有这个:

import re

sourceString="Yesterday I had a pizza for lunch it was tasty\n";
sourceString+="today I am thinking about grabbing a burger and tomorrow it\n"; 
sourceString+="will probably be some fish if I am lucky\n\n\n";
sourceString+="see you later!"

with open('keyWords.txt','r') as f: 
    for keyword in f:
        regexPattern= keyword+".*";
        patternObject=re.compile(regexPattern,re.MULTILINE);
        match=patternObject.search(sourceString);
        if match:
            print("Match found for "+keyword)
            print(match.group())
        else:
            print("warning: no match found for :"+ keyword)

其中 keyWords.txt 将包含以下内容:

pizza
steak
fish

但这会破坏代码,因为不知何故,只有文件中的 LAST 关键字会成功匹配(如果存在匹配项)。

什么给了?

【问题讨论】:

  • 不要只是假设它是一个错误。这仅仅是因为每一行的末尾都有一个换行符,而您没有考虑到这一点。
  • ..这意味着由于我没有考虑换行符,程序有错误吗?我没有说语言规范有缺陷
  • 对不起;我误会了。

标签: python regex file-io


【解决方案1】:
with open('keyWords.txt','r') as f: 
    for keyword in f:
        regexPattern = keyword.strip() + ".*";

使用strip()keyword 中删除任何newline 字符。如果您确定不会有任何前导空格,rstrip() 就足够了。

【讨论】:

  • 这解决了问题。努力
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2018-10-08
相关资源
最近更新 更多