【问题标题】:Checking text files for certain strings in python在python中检查某些字符串的文本文件
【发布时间】:2016-03-08 19:47:41
【问题描述】:

我正在编写一个 Python 代码,该代码将在数千个文本文件中查找某些字符串,然后将这些文本文件的名称附加到两个列表之一。我正在尝试使用带有多个参数的 if 语句来做到这一点:

    # up here would be other code
    #
 with open("/home/textfile.txt", 'r') as f:
        textfile = f.read()
 if "this phrase" in textfile or "that phrase" in textfile and not "not this phrase" in textfile and not "not that phrase" in textfile:
    return True
 elif "not this phrase" in textfile or "not that phrase" in textfile:
    return False

现在在我的代码中,这些 if 语句中有更多参数,但由于某种原因,当我得到包含“这个短语”或“那个短语”的文本文件列表时,其中一些还包含“不是这个短语” .为什么会这样?是因为我在 if 语句中使用了太多参数吗?该程序的主要目标是将文本文件名附加到一个列表或另一个列表中,具体取决于是否将TrueFalse 返回给主函数。

【问题讨论】:

  • 这是一个包含文本文件信息的字符串。在这里,我将快速编辑问题。

标签: python string file search text


【解决方案1】:

你需要对你的条件进行适当的分组,例如:

if (
    ("this phrase" in textfile or "that phrase" in textfile) and not (
    "not this phrase" in textfile or "not that phrase" in textfile)
):
    return True

【讨论】:

    【解决方案2】:

    同意尼克的回答。但是您说 if 语句中还有许多其他参数,因此您不想将所有这些语句都写在 if 循环中。

    我建议使用两个列表。这是一些示例代码。

    注意:请记住,这是一个快速而肮脏的解决方案。您可以根据自己的喜好使用生成器而不是列表(如果您的模式计数很高)、使用 lambda 函数来减少行数(尽管看起来很复杂)等来即兴发挥。

    contain_lst = ['pattern1', 'p2', 'p3']
    not_contain_lst = ['ncp1', 'ncp2', 'ncp3', 'ncp4']
    for each_file in files_list:
        with open(each_file) as f:
            data = f.read()
        contain_match = 1
        for each_contain_pattern in contain_lst:
            if each_contain_pattern in data:
                contain_match = 0
        not_contain_match = 0
        for each_not_contain_pattern in not_contain_lst:
            if each_not_contain_pattern in data:
                not_contain_match = 1
        if contain_match and not not_contain_match:
            print "File %s has all the needed patterns and doesn't have the not needed patterns" % each_file
        else:
            print "ERROR- File %s doesn't match the requirements" % each_file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多