【问题标题】:Find multiple instances of a string in a text file - python在文本文件中查找字符串的多个实例 - python
【发布时间】:2014-04-27 05:25:12
【问题描述】:

我正在尝试在文本文件中查找字符串的多个实例,但我只能找到一种方法来查找第一个实例。我尝试了各种 while 和 for 循环都无济于事,我一直在寻找答案。在 python 中最有效的方法是什么?

movinf = open("movinf.txt", "a")
        match = re.search('"string":([^,]+)', name)
        if match:
            result = match.group(1)
            movinf.write(result + "\n")
        else:
            pass
        movinf.close()

【问题讨论】:

  • 您的输入是什么,您的预期输出是什么?
  • 我偷偷地怀疑您正在尝试使用正则表达式解析 JSON 文件。

标签: python string loops if-statement for-loop


【解决方案1】:

您只运行一次块,因此只得到一个结果。请改用re.findall

match = re.findall('"string":([^,]+)', name)
if len(match) > 0:
    movinf.write("\n".join(match))
movinf.close()

【讨论】:

    【解决方案2】:

    你可以试试re.findall()

    p = re.pattern('"string":([^,]+)')
    print p.findall(name)
    

    【讨论】:

      【解决方案3】:

      以下程序使用简单的文件和列表操作:

      str1 = raw_input("Enter the string you want to search : ")
      with open("C:\\Users\\priyank\\Desktop\\movinf.txt","r") as movinf:
          listp = movinf.readlines()
      count =0
      for i in range(0, len(listp)):
          if str1 in listp[i]:
              # do something
              count=count+1
      print "number of word exist in file :" + str(count)
      

      【讨论】:

        猜你喜欢
        • 2021-05-13
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        • 2015-07-14
        相关资源
        最近更新 更多